Backbone.js 从fetch到表行的响应
这是一个集两个问题于一身的小问题。我试图在获取表行/数据后呈现响应Backbone.js 从fetch到表行的响应,backbone.js,backbone-views,Backbone.js,Backbone Views,这是一个集两个问题于一身的小问题。我试图在获取表行/数据后呈现响应 UsersRow = Backbone.View.extend({ template: _.template("-"), tagName: 'td', initialize: function() { this.users = new Collections.AllUsers(); this.users.fetch({
UsersRow = Backbone.View.extend({
template: _.template("-"),
tagName: 'td',
initialize: function() {
this.users = new Collections.AllUsers();
this.users.fetch({
success: function(response) {
this.response = response;
console.log(JSON.stringify(this.response));
return this.response;
}
});
// these two are undefined
console.log(JSON.stringify(this.response));
console.log(JSON.stringify(this.users.response));
},
render: function(options) {
return this;
}
});
第一个console.log工作得很好,可以获取所有应该获取的内容。第二个,一点也不。怎么了
另外,如何将其呈现给每个表行
谢谢。在回答第一个问题时,请在调用fetch后立即登录,而不是在成功回调中 获取是异步的,当您尝试记录日志时,不能保证返回结果。我已经注释了
initialize
函数,以显示代码的执行顺序。调用success
后,需要执行依赖此响应的所有代码
initialize: function() {
// 1
this.users = new Collections.AllUsers();
// 2
this.users.fetch({
// 4
// Success will be called after the async request completes
success: function(response) {
this.response = response;
console.log(JSON.stringify(this.response));
return this.response;
}
});
// 3
console.log(JSON.stringify(this.response));
console.log(JSON.stringify(this.users.response));
}
试试这个
var UserModel = Backbone.Model.extend({});
var UserCollection = Backbone.Collection.extend({
model: UserModel,
url: "http://example.com/get_all_users.php",
parse: function(data) {
return data;
}
});
var UsersRow = Backbone.View.extend({
el: $("#page"),
render: function() {
var that = this;
this.collection = new UserCollection();
this.collection.fetch({
type: "GET",
contentType: 'application/json',
dataType: "json",
success: function(collection, response) {
var template = _.template(userTemplate, {
users: that.collection.models
});
that.$el.html(template);
},
error: function(collection, response) {
alert("error");
}
});
}
});
return UsersRow;
您可以使用web服务请求和响应JSON数据
您可以访问这些网站以供参考
关于渲染到表行的第二个问题,到目前为止,您有什么经验?您可以尝试查看-我曾多次使用它将集合呈现到表中。如果您对我的代码有任何问题,请告诉我。@Dato'MohammadNurdin在执行return UsersRow时获得未捕获的SyntaxError:非法返回语句(匿名函数);试着看一下这个示例代码。那么,在异步完成之后,如何在呈现函数中调用this.response呢?是的。如果需要在render中使用
this.response
,则可能需要调用this.render()设置this.response=response
后的code>;