为什么我不能使用this.posts成功函数呢?
也许我不了解范围,但是在以下方面:
Maybe I am not understanding scoping but in the following:
AisisWriter.Routers.Posts = Backbone.Router.extend({
writer_posts: null,
posts: null,
routes : {
'': 'index'
},
initialize: function() {
this.writer_posts = new AisisWriter.Collections.Posts();
},
index: function() {
var self = this;
this.writer_posts.fetch({
reset: true,
success: function(collection, response, options){
this.posts = collection;
console.log(this.posts);
}
});
console.log(self.posts)
}
});
在success: function(){}
控制台日志内的
中,有两个帖子.看起来像这样:
inside the success: function(){}
the this.posts
console log has two posts in it. it looks like:
child {length: 1, models: Array[1], _byId: Object, constructor: function, model: function…}
但是当我尝试在提取调用之外使用this.posts
时,它返回null.这是为什么? this
的作用域是否不正确?还是我做错了什么?
But when I try and use this.posts
out side the fetch call, it returns null. Why is that? Is this
not scoped properly? or am I doing something wrong?
您之所以无法访问this.posts,是因为它的执行早于获得响应的时间.您甚至不必将'this'保存在自变量中.要检查它,只需在初始化函数中添加以下行:
You are not being able to get access to your this.posts only because it is executed sooner than you get the response. You even don't have to save 'this' in the self variable. To check it just add in the initialize function this line:
this.listenTo(this.writer_posts, 'reset', this.test);
然后创建测试功能:
test: function() { console.log(this.posts); }
您会看到收藏集已正确保存.
As you will see collection is saved properly.