Backbone js collection of collections issue

后端 未结 1 974
無奈伤痛
無奈伤痛 2020-12-31 21:17

I\'m running into an isssue when I try to create a collection of collections using backbone js. Here is the code :

Models and Collections :

var Track         


        
相关标签:
1条回答
  • 2020-12-31 21:54

    I think your problem is your default tracks attribute in PlayList:

    var Playlist = Backbone.Model.extend({
        defaults : {
            name : "",
            tracks : new TrackCollection,
        }
    });
    

    Backbone will shallow-copy the defaults when creating new instances:

    defaults model.defaults or model.defaults()
    [...]
    Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances.

    The result is that every single PlayList instance that uses the default tracks will be using exactly the same TrackCollection as its tracks attribute and that TrackCollection will be the one referenced in the defaults.

    The easiest solution is to use a function for defaults:

    var Playlist = Backbone.Model.extend({
        defaults : function() {
            return {
                name : "",
                tracks : new TrackCollection,
            };
        }
    });
    

    That way the defaults function will be called when defaults are needed and each time defaults is called you'll get a brand new TrackCollection in the default tracks attribute.

    Here's a quick rule of thumb for you:

    If you want to put anything other than strings, numbers, or booleans in defaults, use a defaults function instead of a defaults object.

    0 讨论(0)
提交回复
热议问题