gpt4 book ai didi

backbone.js - Backbone JS - this.model.models 而不是 this.collection?

转载 作者:行者123 更新时间:2023-12-05 00:31:52 24 4
gpt4 key购买 nike

我是 Backbone JS 的新手,一直在关注 Christopher Coenraets Wine Cellar tutorial .

这一切都很好而且花花公子,但我不明白他是如何使用 this.model.models访问集合而不是 this.collection .此外,当我尝试将代码更改为后者时,似乎 this.collection未定义。

window.WineListView = Backbone.View.extend({

tagName:'ul',

initialize:function () {
this.model.bind("reset", this.render, this);
},

render:function (eventName) {
_.each(this.model.models, function (wine) {
$(this.el).append(new WineListItemView({model:wine}).render().el);
}, this);
return this;
}

});

最佳答案

有两件事让你感到沮丧:

  • 您可以根据需要在 View 中注入(inject)集合。通常的方法是传递一个集合属性,但这里它是作为路由器中的模型传递的:
    this.wineList = new WineCollection();
    this.wineListView = new WineListView({model:this.wineList});
  • collection.models在集合中保存模型的原始数组

    models collection.models
    Raw access to the JavaScript array of models inside of the collection. Usually you'll want to use get, at, or the Underscore methods to access model objects, but occasionally a direct reference to the array is desired.


  • 如果你想使用 this.collection在您看来,您应该将路由器修改为
    this.wineList = new WineCollection();
    this.wineListView = new WineListView({collection: this.wineList});

    然后您可以将其用作
    window.WineListView = Backbone.View.extend({
    tagName: 'ul',

    initialize: function () {
    this.collection.bind("reset", this.render, this);
    },

    render: function (eventName) {
    // Backbone proxies Underscore methods on collections
    // _.each(this.collection.models, function (wine) {

    this.collection.each(function (wine) {
    $(this.el).append(new WineListItemView({model: wine}).render().el);
    }, this);

    return this;
    }
    });

    关于backbone.js - Backbone JS - this.model.models 而不是 this.collection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14156726/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com