我遇到的情况是我的fetch工作正常,我可以看到我的骨干集合中的数据,如果我进入我从集合中将项目分配给模型var或暂停一秒钟的方法或者两个,一切都很好:代码行this.member被填充
this.member = this.members.get(1);
。如果我只是让代码运行,我最终会将null模型传递给我的视图。我不明白我错过了什么。在访问集合之前,是否需要绑定集合中的数据?我想要爱上Backbone,但到目前为止,她一直是个残酷的情妇......
`
//create the namespace
var Endeavor = {
Models: {},
Collections: {},
Views: {},
Templates: {}
};
Endeavor.Models.Member = Backbone.Model.extend({
idAttribute: "Id"
});
Endeavor.Collections.Members = Backbone.Collection.extend({
model: Endeavor.Models.Member,
url: "Http://localhost:60000/api/members/" + "1", // $.cookie('UserId')
initialize: function () {
console.log("Members collections init");
}
});
Endeavor.Views.MemberView = Backbone.View.extend({
id: "memberForm",
template: "#memberTemplate",
initialize: function () {
console.log('init member view');
},
render: function () {
console.log('memberView render called');
console.log(this.model.toJSON());
var html = $(this.template).tmpl();
$(this.el).html(html);
$("#Name").text = this.model.Name;
}
});
jQuery(document).ready(function () {
// router
Endeavor.Router = Backbone.Router.extend({
routes: {
"": "lists",
},
lists: function () {
this.members = new Endeavor.Collections.Members();
this.members.fetch();
this.member = this.members.get(1);
var memberView = new Endeavor.Views.MemberView({ model: this.member });
memberView.render();
$("#content").html(memberView.el);
}
});
// populate local variables
var appRouter = new Endeavor.Router();
Backbone.history.start();
});
`。
答案 0 :(得分:2)
Members.fetch
是异步调用。尝试在render
members
事件中reset
查看,或在success
方法中传递fetch
回调,或致电this.members.fetch({async: false})
。有很多不同的选择。