4
votes

Why does this trigger the "change" event on the Backbone Collection?

data.json file:

[
    {
        "id": 1,
        "name": "Alex",
        "comments": [
            {
                "id":5
            }
        ]
    },
    {
        "id": 2,
        "name": "Tom",
        "comments": []
    }
]

data for model:

data = [
    {
        id: 1,
        name: "Alex",
        comments: [
            {
                id:5
            }
        ]
    },
    {
        id: 2,
        name: "Tom",
        comments: []
    }
]

var Model = Backbone.Model.extend({
    initialize: function () {
        console.log('init model');
    }
});

var View = Backbone.View.extend({
    initialize: function () {
        console.log('init view');
    }
});

var Collection = Backbone.Collection.extend({
    model: Model,
    url: "data.json",

    initialize: function () {
        console.log('init collection');
    }
});

Add data to model:

var collection = new Collection(data);

collection.on('change', function () {
    console.log('change');
})

Fetch:

 collection.fetch({
        update: true,
        merge: true
    })

After fetch we see 'change' in the console.

Please, help me. I must use this event, but I don't want trigger event on "comments", if the data has not changed.

1

1 Answers

2
votes

Upon receiving the response from collection.fetch(), Backbone goes through each model in the response and checks if it is already in the local collection. If so, then it goes through each attribute of the response's model and checks if the local model has that same attribute and if it is equal.

This is all fine and dandy, but, as you might have expected, two arrays are NOT going to be equal in JavaScript:

[] === [] // false

Thus, when Backbone gets to the comments attribute of the response, although the values from the response and locally appear equal, they are NOT equal (according to JavaScript). Backbone sees this as a difference and fires a change event.