5

我试图理解模型和视图之间的关系。我已经尝试构建一个模型和视图来渲染该模型。

我得到了Cannot call method 'toJSON' of undefined我理解的错误,因为模型的实际实例没有被发送到视图。

我觉得在视图的初始化中缺少一些东西?

该模型:

var sticky = Backbone.Model.extend({

defaults: {
    title:"",
    content:"",
    created: new Date()

},

initialize: function() {
    console.log("sticky created!");

}

}); 

风景:

var stickyView = Backbone.View.extend({

tagName:"div",
className:"sticky-container",

initialize: function() {
    this.render();
    console.log("stickyView created!");
},

render: function() {
    $("#content-view").prepend(this.el);
    var data = this.model.toJSON(); // Error: Cannot call method 'toJSON' of undefined 
    console.log(data);
    var source = $("#sticky-template").html();
    var template = Handlebars.compile(source);
    $(this.el).html(template(data));
    return this;
}

});

创建视图的新模型和新实例:

var Sticky = new sticky({title:"test"});

var StickyView = new stickyView();
4

1 回答 1

7

您必须将模型实例传递给您的视图,Backbone 将完成其余的工作

constructor / initialize new View([options])
有几个特殊选项,如果通过,将直接附加到视图:模型、集合、el、id、className、tagName 和属性。

这意味着你会像这样创建你的视图

var StickyView = new stickyView({model: Sticky});

当你使用它时,你可以传递你编译的模板和你希望设置为你的视图元素的 DOM 节点(tagName并从你的视图定义中删除 and className)以避免严​​格的耦合:

var stickyView = Backbone.View.extend({

    initialize: function(opts) {
        this.template = opts.template;
        this.render();
        console.log("stickyView created!");
    },

    render: function() {
        var data = this.model.toJSON();
        console.log(data);

        this.$el.html(this.template(data));

        return this;
    }

});

var StickyView = new stickyView({
    model: Sticky, 
    el: '#content-view',
    template: Handlebars.compile($("#sticky-template").html())
});
于 2013-05-11T17:04:16.737 回答