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

时间:2013-05-11 15:54:02

标签: backbone.js models 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!");

}

}); 

观点:

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();

1 个答案:

答案 0 :(得分:7)

您必须将模型实例传递给视图Backbone will do the rest

  

构造函数/初始化新视图([options])
  有几个特殊选项,如果通过,将直接附加到   视图:模型,集合,el,id,className,tagName和   属性。

这意味着您可以像这样创建视图

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

当您使用它时,您可以将已编译的模板和要设置的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())
});