Search code examples
javascriptbackbone.jsbackbone-views

Backbone.js. Make change event correctly


I'm writing Todo app with Backbone.js

You can see part of my code below. Model:

 var Todo = Backbone.Model.extend({
    defaults : {
        title: 'Task Title',
        complete: false
    },
    initialize: function(){
        this.on("change:complete", function () {
            alert("foo");
        });
    }
});

View:

var AppView = Backbone.View.extend({
        collection: todoCollection,
        el: 'body',
        events: {
            'click #tasks li .complete-task' : 'toggleComplete'
        }
        toggleComplete: function (e) {
            var modelCid = $(e.target).parent('li').attr('id');

             if ( this.collection.get(modelCid)['complete'] ){
                this.collection.get(modelCid)['complete'] = false;
             } else {
                 this.collection.get(modelCid)['complete'] = true;
             };
        }
    });

But something working wrong and change event in the model doesn't working. I can't understand where I have mistakes. Help me, please. 10q.


Solution

  • As per the Backbone Documentation:

    Set model.set(attributes, [options])

    Set a hash of attributes (one or many) on the model. If any of the attributes change the model's state, a "change" event will be triggered on the model. Change events for specific attributes are also triggered, and you can bind to those as well, for example: change:title, and change:content. You may also pass individual keys and values.

    So you need to be using the set method on the model for these events to be fired. So you would need to use something like this:

    this.collection.get(modelCid).set('complete',false);