Backbone.js 未在主干视图中调用渲染
这是我的脊梁骨:Backbone.js 未在主干视图中调用渲染,backbone.js,Backbone.js,这是我的脊梁骨: App.Models.Count = Backbone.Model.extend({ url: this.url, initialize: function() { this.fetch({ success: function(data, response) { this.count = data.get('count');
App.Models.Count = Backbone.Model.extend({
url: this.url,
initialize: function() {
this.fetch({
success: function(data, response) {
this.count = data.get('count');
console.log(this.count); // 9, correct answer
}
});
}
});
App.Views.Count = Backbone.View.extend({
tagName: 'span',
initialize: function(options) {
this.count = this.options.count;
console.log(options); // returns correctly
this.model.on('reset', this.render, this);
},
render: function() {
console.log('test'); // not called
this.$el.html(this.model.toJSON());
return this;
}
});
在我看来:
var mc = new (App.Models.Count.extend({'url' : 'main-contact-count'}))();
var mcv = new (App.Views.Count.extend({ model: mc }))();
console.log(mcv); // 9, correct answer
$('#contactCount').html(mcv);
如您所见,从未调用我的
render
方法。此外,根据我在Firebug中看到的console.log,我的视图似乎在我的模型之前被调用。这是因为异步吗?为什么不调用render
?您正在以一种时髦的方式使用主干网。以下是更标准的方法:
App.Models.Count = Backbone.Model.extend({
urlRoot: "main-contact-count"
});
App.Views.Count = Backbone.View.extend({
tagName: 'span',
initialize: function(options) {
this.model.on('change', this.render, this);
},
render: function() {
console.log('test');
this.$el.html(this.model.toJSON());
return this;
}
});
在路由器中:
var mc = new App.Models.Count();
var mcv = new App.Views.Count({model: mc});
mc.fetch();
$('#contactCount').html(mcv.el);
编辑
事实证明,您正在收听主干模型上的“重置”。这永远不会发生。尝试侦听“更改”而不是重置:
this.model.on('change', this.render, this);
Render
仍然不会触发该更改。如果我让您的更改自调用,我会得到一个错误,该错误此错误。\u configure不是一个函数。
您说的是快速修复。有更好的方法吗?我想动态地将url传递给模型,因为url随路径而变化。我注意到您正在收听的是“重置”而不是“更改”。试试“改变”吧。