Backbone.js : change not firing on model.change()

53,391

Solution 1

I'm pretty new to backbone and I was having this same problem.

After doing some research, I found a few posts that shed a little bit more light on why this was happening, and eventually things started to make sense:

Question 1

Question 2

The core reason has to do with the notion of reference equality versus set/member equality. It appears that to a large extent, reference equality is one of the primary techniques backbone uses to figure out when an attribute has changed.

I find that if I use techniques that generate a new reference like Array.slice() or _.clone(), the change event is recognized.

So for example, the following code does not trigger the event because I'm altering the same array reference:

this.collection.each(function (caseFileModel) {
    var labelArray = caseFileModel.get("labels");
    labelArray.push({ Key: 1, DisplayValue: messageData });
    caseFileModel.set({ "labels": labelArray });
});

While this code does trigger the event:

this.collection.each(function (caseFileModel) {
    var labelArray = _.clone(caseFileModel.get("labels")); // The clone() call ensures we get a new array reference - a requirement for the change event
    labelArray.push({ Key: 1, DisplayValue: messageData });
    caseFileModel.set({ "labels": labelArray });
});

NOTE: According to the Underscore API, _.clone() copies certain nested items by reference. The root/parent object is cloned though, so it will work fine for backbone. That is, if your array is very simple and does not have nested structures e.g. [1, 2, 3].

While my improved code above triggered the change event, the following did not because my array contained nested objects:

var labelArray = _.clone(this.model.get("labels"));
_.each(labelArray, function (label) {
    label.isSelected = (_.isEqual(label, selectedLabel));
});
this.model.set({ "labels": labelArray });

Now why does this matter? After debugging very carefully, I noticed that in my iterator I was referencing the same object reference backbone was storing. In other words, I had inadvertently reached into the innards of my model and flipped a bit. When I called setLabels(), backbone correctly recognized that nothing changed because it already knew I flipped that bit.

After looking around some more, people seem to generally say that deep copy operations in javascript are a real pain - nothing built-in to do it. So I did this, which worked fine for me - general applicability may vary:

var labelArray = JSON.parse(JSON.stringify(this.model.get("labels")));
_.each(labelArray, function (label) {
    label.isSelected = (_.isEqual(label, selectedLabel));
});
this.model.set({ "labels": labelArray });

Solution 2

Interesting. I would have thought that .set({cas:someArray}) would have fired off a change event. Like you said, it doesn't seem to, and I can't get it to fire with .change() BUT, I can get the events to work if I just do model.trigger('change') or model.trigger('change:attribute')

This would allow you to trigger the change event without that random attribute hack.

If someone could explain what is going on with events, Backbone, and this code, that would help me learn something too... Here is some code.

Ship = Backbone.Model.extend({
    defaults: {
        name:'titanic',
        cas: new Array()
    },
    initialize: function() {
        this.on('change:cas', this.notify, this);
        this.on('change', this.notifyGeneral, this);
    },
    notify: function() {
        console.log('cas changed');
    },
    notifyGeneral: function() {
        console.log('general change');
    }
});

myShip = new Ship();

myShip.set('cas',new Array());
    // No event fired off

myShip.set({cas: [1,2,3]});  // <- Why? Compared to next "Why?", why does this work?
    // cas changed
    // general change

myArray = new Array();
myArray.push(4,5,6);

myShip.set({cas:myArray});  // <- Why?
    // No event fired off
myShip.toJSON();
    // Array[3] is definitely there

myShip.change();
    // No event fired off

The interesting part that might help you:

myShip.trigger('change');
    // general change
myShip.trigger('change:cas');
    // cas changed

I find this interesting and I hope this answer will also spawn some insightful explanation in comments which I don't have.

Share:
53,391
Atyz
Author by

Atyz

Updated on June 18, 2020

Comments

  • Atyz
    Atyz almost 4 years

    I'm facing a "change event not firing" issue on Backbone.js =/

    Here my view of User model :

        window.UserView = Backbone.View.extend({
    
            ...
    
            initialize: function()
            {
                this.model.on('destroy', this.remove, this);
    
                this.model.on('change', function()
                {
                   console.log('foo');
                });
            },
    
            render: function(selected)
            {
                var view = this.template(this.model.toJSON());
    
                $(this.el).html(view);
    
                return this;
            },
    
            transfer: function(e)
            {                
                var cas = listofcas;
    
                var transferTo = Users.getByCid('c1');
                var transferToCas = transferTo.get('cas');
    
                this.model.set('cas', cas);
                console.log('current model');
                console.log(this.model);
    
                //this.model.change();
                this.model.trigger("change:cas");
                console.log('trigger change');
    
                transferTo.set('cas', transferToCas);
                console.log('transferto model');
                console.log(transferTo);
    
                //transferTo.change();
                transferTo.trigger("change:cas");
                console.log('trigger change');
    
            }
    
        });
    

    Here, the User model :

    window.User = Backbone.Model.extend({
    
            urlRoot: $('#pilote-manager-app').attr('data-src'),
    
            initialize: function()
            {
                this.set('rand', 1);
                this.set('specialite', this.get('sfGuardUser').specialite);
                this.set('name', this.get('sfGuardUser').first_name + ' ' + this.get('sfGuardUser').last_name);
                this.set('userid', this.get('sfGuardUser').id);
                this.set('avatarsrc', this.get('sfGuardUser').avatarsrc);
                this.set('cas', new Array());
    
                if (undefined != this.get('sfGuardUser').SignalisationBouclePorteur) {
    
                    var cas = new Array();
    
                    _.each(this.get('sfGuardUser').SignalisationBouclePorteur, function(value)
                    {
                        cas.push(value.Signalisation);
                    });
    
                    this.set('cas', cas);
    
                }
            }
        });
    

    In User model, there is "cas" attribute, which is an array of objects.

    I read in others topics that change events are not fire on model.set if attributes are not a value.

    So, I try to trigger directly the change event with model.change() method. But, I have no "foo" log in my console ...

  • radicand
    radicand almost 12 years
    What version of backbone/underscore are you using? Your sample code fires the changes for me in the Chrome debugger with BB 0.9.2 & _ 1.3.2: > myShip = new Ship(); > myShip.set('cas',new Array()); > myShip.set({cas: [1,2,3]}); cas changed general change > myArray = new Array(); > myArray.push(4,5,6); > myShip.set({cas:myArray}); cas changed general change
  • Kalamarico
    Kalamarico almost 12 years
    With the same versions of BB & _ like orangewarp the events fires too. But in another code, i have the same problem, setting an array not fires the event.... searching the reason...
  • Dmitry
    Dmitry about 11 years
    stringifying and parsing - neat!
  • Brandon
    Brandon about 11 years
    +1 this is a better solution than the accepted answer. I was hoping I could trigger the change event myself, but didn't know how. I was about to create a dummy scalar attribute just to trigger changes, but then scrolled down to this answer. Thanks!
  • Josh Mc
    Josh Mc about 10 years
    Thank you so much, I only read the first few sentences, but this helped me straight away, cheers.
  • Daniel Roizman
    Daniel Roizman almost 10 years
    Even with JSON.parse(JSON.stringify I find that arrays don't always trigger an update. I usually .reverse() the array and then sort it on the other side if order is important.
  • Erico Chan
    Erico Chan almost 10 years
    using _.extend({}, this.model.get("labels")) can also return a deep copy of the object
  • tvshajeer
    tvshajeer about 9 years
    @orangewarp , How to apply this method on textbox value is change. should i use this.on('change:input.txtclass', this.notify, this); when i have multiple textboxes with same change event <input type="text" class="txtclass"></input> <input type="text" class="txtclass"></input>
  • jmk2142
    jmk2142 about 9 years
    @tvshajeer Not quite. I think what you're trying to do is hook up DOM events via jQuery and you're mixing them up with Backbone Events which are primarily used to run handlers on Models and such. Inputs won't have Backbone.Events extended and won't react to the "change" event I don't think. With backbone, everything tends to be data driven... so your View would set the model data based on your input UI and then your View would be listening to the model attr for the 'change' event to then fire off this.notify. Also, you should be using the newer .listenTo rather than .on at this point.
  • Thomas
    Thomas almost 4 years
    This is bad behavior. It should trigger the change event right on myShip.set('cas',new Array()); because you are setting a new array. equal != same.