1

我正在阅读关于构建酒窖应用程序的 Backbone 教程http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/ 。教程的作者没有解释清楚一点,我无法从文档中弄清楚。即,this.model.models您在下面的渲染函数视图中看到的

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;
    }

});

这个视图的模型实际上是一个集合

list:function () {
        this.wineList = new WineCollection();
        this.wineListView = new WineListView({model:this.wineList});

该系列将Wine作为其模型

window.WineCollection = Backbone.Collection.extend({
    model:Wine,
    url:"../api/wines"
});

所以,当 WineListView 被实例化时,它this.model实际上就是 Wine List Collection。并且,从文档中,models可以访问集合中的模型数组

modelscollection.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.model已经是 wine 的集合(由于集合在视图中被声明为模型),为什么有必要这样做this.model.models?基本上再次获得收藏?

4

2 回答 2

1

看起来这本质上是一种风格选择。编码

_.each(this.model.models, function (wine) {
    $(this.el).append(...);
}, this);

简单地遍历集合中的模型,并且应该等效于:

this.model.each(function (wine) {
    $(this.el).append(...);
}, this);

我原以为第二个版本更容易阅读,但每个版本都是他/她自己的......

于 2012-04-17T20:39:00.987 回答
1

就我而言,要使其正常工作,我必须执行以下操作:

    _.each(this.model.models, function (foto) {
        console.log(foto.attributes);
        $(this.el).append(new App.view.foto.foto({model:foto.attributes}).render().el);
    }, this);

不知道为什么访问 .attributes 会起作用,我是否错过了任何转换?

我从数据库引导以下 JSON 字符串:

[{
    "fid": 1,
    "imagen": "sample_colors.jpg",
    "width": "110",
    "height": "110",
    "dimension_id": 1,
    "seccion_id": 1,
    "estado": 0,
    "fecha": {
        "date": "2012-06-27 23:02:27",
        "timezone_type": 2,
        "timezone": "PDT"
    }
}, {
    "fid": 2,
    "imagen": "sample_colors.jpg",
    "width": "110",
    "height": "110",
    "dimension_id": 1,
    "seccion_id": 1,
    "estado": 1,
    "fecha": {
        "date": "2012-06-27 12:03:02",
        "timezone_type": 2,
        "timezone": "PDT"
    }
}, {
    "fid": 3,
    "imagen": "sample_colors.jpg",
    "width": "110",
    "height": "110",
    "dimension_id": 1,
    "seccion_id": 1,
    "estado": 2,
    "fecha": {
        "date": "2012-06-27 12:03:20",
        "timezone_type": 2,
        "timezone": "PDT"
    }
}]
于 2012-06-29T20:03:11.773 回答