骨干:使用“model.models”

时间:2012-04-17 20:28:45

标签: backbone.js

我正在阅读关于构建酒窖应用程序的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已经是葡萄酒的集合(由于集合在视图中被声明为模型),为什么有必要进行this.model.models?基本上再次获得该集合?

2 个答案:

答案 0 :(得分:1)

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

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

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

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

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

答案 1 :(得分: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"
    }
}]
相关问题