开发者

Backbone.js Collection model value not used

Backbone is not using the model specified for the collection. I must be missing something.

App.Models.Folder = Backbone.Model.extend({
  initialize: function() {
    _.extend(this, Backbone.Events);

    this.url = "/folders";
    this.items = new App.Collections.FolderItems();
    this.items.url = '/folders/' + this.id + '/items';
  },

  get_item: function(id) {
    return this.items.get(id);
  }
});

App.Collections.开发者_运维问答FolderItems = Backbone.Collection.extend({
  model: App.Models.FolderItem
});

App.Models.FolderItem = Backbone.Model.extend({
  initialize: function() {
    console.log("FOLDER ITEM INIT");
  }
});


var folder = new App.Models.Folder({id:id})
folder.fetch();

// later on change event in a view
folder.items.fetch();

The folder is loaded, the items are then loaded, but they are not FolderItem objects and FOLDER ITEM INIT is never called. They are basic Model objects.

What did I miss? Should I do this differently?

EDIT: Not sure why this works vs the documentation, but the following works. Backbone 5.3

App.Collections.FolderItems = Backbone.Collection.extend({
  model: function(attributes) {
    return new App.Models.FolderItem(attributes);
  } 
});


the problem is order of declaration for your model vs collection. basically, you need to define the model first.

App.Models.FolderItem = Backbone.Model.extend({...});

App.Collections.FolderItems = Backbone.Collection.extend({
  model: App.Models.FolderItem
});

the reason is that backbone objects are defined with object literal syntax, which means they are evaluated immediately upon definition.

this code is functionality the same, but illustrates the object literal nature:

var folderItemDef = { ... };

var folderItemsDef = {
  model: App.Models.FolderItem
}

App.Models.FolderItem = Backbone.Model.extend(folderItemDef);

App.Collections.FolderItems = Backbone.Collection.extend(folderItemsDef);

you can see in this example that folderItemDef and folderItems Def are both object literals, which have their key: value pairs evaluated immediately upon definition of the literal.

in your original code, you defined the collection first. this means App.Models.FolderItem is undefined when the collection is defined. so you are essentially doing this:

App.Collection.extend({
  model: undefined
});

By moving the model definition above the collection definition, though, the collection will be able to find the model and it will be associated correctly.

FWIW: the reason your function version of setting the collection's model works, is that the function is not evaluated until the app is executed and a model is loaded into the collection. at that point, the javascript interpreter has already found the model's definition and it loads it correctly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜