为什么我不能用这个.贴出成功功能
Why can I not use this.posts out side the success function?
也许我不理解范围,但在以下:
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(){}
中,this.posts
控制台日志中有两个帖子。它看起来像:
child {length: 1, models: Array[1], _byId: Object, constructor: function, model: function…}
但是当我尝试使用this.posts
取出调用时,它返回null。为什么呢?this
的作用域是否不正确?还是我做错了什么?
您无法访问您的this。post仅仅是因为它在您得到响应之前就被执行了。你甚至不需要在self变量中保存this。要检查它,只需在这一行添加初始化函数:
this.listenTo(this.writer_posts, 'reset', this.test);
然后创建test函数:
test: function() { console.log(this.posts); }
您将看到集合被正确保存。
由于您的fetch可能需要一些时间才能进入success promise,因此下一行将在此之前更快地执行。
index: function() {
var self = this;
this.writer_posts.fetch({
reset: true,
success: function(collection, response, options){
//write your callback function inside the success
//self.afterSuccess(collection);
}
});
},
您可以传递函数的参数并获取它。
afterSuccess: function(collection) {
console.log("the collection has"+JSON.stringify(collection));
}
相关文章:
- Jquery表单插件未显示成功功能
- 成功:功能(数据);不使用命名函数
- 只有在前一个功能成功完成的情况下,我才能正确地启动此功能
- JQuery AJAX没有't获得成功回调功能
- 谷歌登录成功功能在我阻止第三方cookie时没有任何作用
- 成功提交 Web 表单后,Javascript 重置功能将不起作用
- 骨干.js:Save的成功功能根本不起作用
- 如何触发一个新的 X-Editable 从当前功能的成功函数中打开
- ajax内部访问类功能成功
- 如何检查PHP邮件功能是否成功,然后运行一个javascript代码
- Extjs 4上传成功功能没有反应
- 将显示功能应用于ajax成功创建的元素
- 包括成功/失败jQuery / Ajax功能
- 列表框上的EventListener在物品掉落后不再工作[所有javascript功能在成功掉落后停止]
- AJAX成功服务器端功能
- 为什么我不能用这个.贴出成功功能
- Gulp通知全局成功功能
- 如何添加成功功能?
- “成功”功能是如何运作的,我该如何模仿它
- AJAX的成功功能是有效的,但文件是't正在运行