我的代码中出现意外行为
我有以下代码:
var myApp = {
Models: {},
Views: {},
Collections: {},
Controllers: {},
init: function() {
new this.Controllers.Main();
Backbone.history.start();
}
}
myApp.Models.User = Backbone.Model.extend({
idAttribute : '_id',
url : 'currentUser',
initialize : function() {
this.fetch();
}
});
myApp.Controllers.Main = Backbone.Controller.extend({
initialize: function() {
this.currentUser = new myApp.Models.User();
},
routes: {
'' : 'index',
},
index: function() {
console.log('index called');
console.log(this.currentUser); // shows the correct object
console.log(this.currentUser.attributes); // empty object ?
console.log(this.currentUser.toJSON()); // empty object ?
console.log(this.currentUser.get('name')); // undefined ?
}
});
$(function() {
myApp.init();
});
我缺少什么?
I have the following code:
var myApp = {
Models: {},
Views: {},
Collections: {},
Controllers: {},
init: function() {
new this.Controllers.Main();
Backbone.history.start();
}
}
myApp.Models.User = Backbone.Model.extend({
idAttribute : '_id',
url : 'currentUser',
initialize : function() {
this.fetch();
}
});
myApp.Controllers.Main = Backbone.Controller.extend({
initialize: function() {
this.currentUser = new myApp.Models.User();
},
routes: {
'' : 'index',
},
index: function() {
console.log('index called');
console.log(this.currentUser); // shows the correct object
console.log(this.currentUser.attributes); // empty object ?
console.log(this.currentUser.toJSON()); // empty object ?
console.log(this.currentUser.get('name')); // undefined ?
}
});
$(function() {
myApp.init();
});
What am i missing ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个异步问题。 Fetch 正在执行异步 Ajax 调用,它将返回,但尚未设置任何值。这样做:
当获取成功并且在模型上设置了 id 时,将调用日志。
This is an asynchronous problem. Fetch is doing an asynchronous Ajax call, it will return but no values will be set yet. Do something like that:
When the fetch succeed and an id is set on the model, the logs will be called.
如果你这样做
new myApp.Models.User();
,你会创建一个新的空User
..它怎么可能有属性..你没有指定一个 id 所以如何从服务器获取它?
而且您没有指定默认值..
所以对我来说这似乎是一致的,不是吗?
If you do
new myApp.Models.User();
, you create a new emptyUser
.. How could it have attributes ..You didn't specify an id so how could it be fetched from the server ?
And you didn't specify defaults values ..
So it seems coherent to me, no ?