好的,超级基本的骨干问题 - 我一直在寻找这个,但尽管有很多类似的问题,但我太慢了,无法得到它。请放心,我感到适当的羞耻。
无论如何,足够的自我鞭笞 - 为什么不渲染?
var app = app || {};
app.Option = Backbone.Model.extend({
url: 'http://localhost:4711/api'
//This url contains the following JSON: {"title": "Blahblah", "author": "Luke Skywalker"};
});
app.View = Backbone.View.extend({
el: 'body',
initialize: function(){
this.model.fetch();
this.model.bind('change', this.render(), this);
},
render: function(){
this.$el.html(this.model.get('title'));
return this;
}
});
$(function() {
var option = new app.Option();
this.homeView = new app.View({ //Tried changing this to a standard var declaration but didn't work
model: option
});
this.homeView.render();
});
所以我期待在屏幕上看到JSON"Blahblah",但我什么也没看到。JSON 正在正确获取(我可以在 firebug 控制台中看到成功的 GET 请求),我想我已经确保在尝试渲染数据之前获取数据......
那么怎么了呢?控制台给我这个错误:"类型错误:(中间值).callback.call 不是一个函数"
谢谢!
一件事是,您在事件绑定中立即调用this.render()
,而不仅仅是绑定回调。请改为执行此操作(使用 listenTo
作为最佳实践):
initialize: function(){
this.listenTo(this.model, 'change', this.render);
this.model.fetch();
}
模型是否有可能实际上没有改变?您可以尝试绑定到 sync
而不是change
以查看是否有效。
您还会渲染两次。一次直接使用 this.homeView.render()
,一次通过事件处理程序。如果您确实想保持模型提取initialize
并绑定到更改事件,则不需要直接渲染。
玩这些,看看这是否不能解决它。
只需在绑定时从 render 方法中删除括号:
this.model.bind('change', this.render, this);
此外,使用on
或listenTo
是一种更好的方法,然后bind
。
我将按以下方式构建骨干骨架:
var app = app || {};
app.Option.Model = Backbone.Model.extend({});
app.Option.Collection = Backbone.Collection.extend({
model : app.Option.Model,
fetch : function(options) {
Backbone.Collection.prototype.fetch.call(this, options);
},
url : function() {
return 'http://localhost:4711/api';
},
parse: function(response) { // this is the ajax call
console.log(response);
}
});
然后在视图中,只需在初始化时调用 fetch 方法:
app.Option.View = Backbone.View.extend({
collection : app.Option.Collection,
initialize : {
this.collection.bind('reset', this.render, this);
this.collection.fetch();
},
render : {
var results = this.collection.toJSON();
console.log(results);
}
});
当我需要调用 Web 服务时,这是我的最小主干骨架。我没有在本地测试过,但这样代码应该可以工作。