gpt4 book ai didi

backbone.js - 获取模型数据到 View backbone.js

转载 作者:行者123 更新时间:2023-12-04 18:10:00 25 4
gpt4 key购买 nike

我试图理解模型和 View 之间的关系。我试过构建一个模型和 View 来渲染该模型。

我收到错误 Cannot call method 'toJSON' of undefined我理解为模型的实际实例没有被发送到 View 。

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

该模型:

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

});

创建 View 的新模型和新实例:
var Sticky = new sticky({title:"test"});

var StickyView = new stickyView();

最佳答案

您必须将模型实例传递给 View ,Backbone will do the rest :

constructor / initialize new View([options])
There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName and attributes.



这意味着你会像这样创建你的 View
var StickyView = new stickyView({model: Sticky});

当你在做的时候,你可以传递你编译的模板和你希望设置为 View 元素的 DOM 节点(并从 View 定义中删除 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())
});

关于backbone.js - 获取模型数据到 View backbone.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16499008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com