为什么我不能用这个.贴出成功功能

Why can I not use this.posts out side the success function?

本文关键字:成功 功能 不能 为什么      更新时间:2023-09-26

也许我不理解范围,但在以下:

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));
}