将模型数据获取到视图backbone.js

sal*_*lly 5 models backbone.js backbone-views

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

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

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

该模型:

var sticky = Backbone.Model.extend({

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

},

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

}

}); 
Run Code Online (Sandbox Code Playgroud)

风景:

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

});
Run Code Online (Sandbox Code Playgroud)

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

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

var StickyView = new stickyView();
Run Code Online (Sandbox Code Playgroud)

nik*_*shr 7

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

构造函数/初始化新视图([options])
有几个特殊选项,如果传递,将直接附加到视图:model,collection,el,id,className,tagName和attributes.

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

var StickyView = new stickyView({model: Sticky});
Run Code Online (Sandbox Code Playgroud)

当你在它的时候,你可以传递你编译的模板和你想要设置为视图元素的DOM节点(tagNameclassName从视图定义中删除)以避免严​​格的耦合:

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())
});
Run Code Online (Sandbox Code Playgroud)