为什么我不能在成功函数之外使用this.posts?

时间:2014-05-29 14:27:57

标签: javascript backbone.js

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

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…}

但是当我尝试在fetch调用旁边使用this.posts时,它返回null。这是为什么? this的范围是否正确?或者我做错了什么?

2 个答案:

答案 0 :(得分:0)

由于您的获取可能需要一段时间才能取得成功,因此承诺下一行将在此之前提前执行。

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

答案 1 :(得分:0)

您无法访问this.posts只是因为它比您收到回复的时间更早执行。你甚至不必保存这个'在自变量中。要检查它,只需在初始化函数中添加以下行:

this.listenTo(this.writer_posts, 'reset', this.test);

然后创建测试功能:

test: function() { console.log(this.posts); }

您将看到正确保存集合。