Javascript Backbone.js:在模型中呈现json数据
好的,超级基本主干问题-我一直在寻找这个问题,但我只是太慢了,尽管有许多类似的问题。请放心,我感到羞耻是适当的 无论如何,足够的自我鞭笞-为什么这不渲染Javascript Backbone.js:在模型中呈现json数据,javascript,json,backbone.js,Javascript,Json,Backbone.js,好的,超级基本主干问题-我一直在寻找这个问题,但我只是太慢了,尽管有许多类似的问题。请放心,我感到羞耻是适当的 无论如何,足够的自我鞭笞-为什么这不渲染 var app = app || {}; app.Option = Backbone.Model.extend({ url: 'http://localhost:4711/api' //This url contains the following JSON: {"title": "Blahblah", "author": "Luke Sk
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请求),我想我已经确保在尝试呈现数据之前获取数据
那怎么了?控制台给我这个错误:“TypeError:(中间值)。callback.call不是函数”
谢谢 一件事是,您正在事件绑定中立即调用
this.render()
,而不仅仅是绑定回调。改为这样做(使用listenTo
了解最佳做法):
是否可能模型实际上没有改变?您可以尝试绑定到sync
,而不是change
,以查看这是否有效
还可以渲染两次。一次直接使用this.homeView.render()
,一次通过事件处理程序。如果您真的想保持模型在initialize
中提取并绑定到更改事件,则不需要直接渲染
玩这些,看看这是否解决不了问题。绑定时只需从渲染方法中删除括号即可:
this.model.bind('change',this.render,this)代码>
此外,在
上使用或列表
是一种比绑定
更好的方法,我将按照以下方式构建主干骨架:
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服务时,这是我的最小主干框架。我没有在本地进行测试,但这样代码应该可以工作 需要明确的是,其中最重要的部分是事件侦听器中的
this.render()
,它应该是this.render
。
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);
}
});