2012-12-29 56 views
3

類似的問題已經在這裏問How do I trigger the success callback on a model.save()?,但仍然沒有答案如何從回調觸發事件。從回調訪問`this`

所以這裏是success在我的代碼中回調,其中我想調用addOne事件來渲染保存的Comment。一切運作良好,除了this.addOne(receivedItem); - 我不能在回調中使用this來觸發此事件。其他地方 - 我可以。

如何解決這個問題?

CommentsListView = Backbone.View.extend({ 
    ... 
    addOne: function (item) { 
     var commentView = new CommentView({ 
      model: item 
     }); 
     this.$el.append(commentView.render().el); 
    }, 
    addNewComment: function (event) { 
     var item = { 
      post_id: this.$('#post_id').val(), 
      text: this.$('#text').val() 
     }; 
     var commentItem = new CommentItem(); 
     commentItem.save({'model':item}, { 
      success: function(receivedItem, response) { 
       this.addOne(receivedItem); // Uncaught TypeError: Object [object Window] has no method 'addOne'. 
      } 
     }, this); 
    } 
}); 
+2

的可能的複製[如何訪問正確的\'這\'/上下文回調裏面?](http://stackoverflow.com/questions/20279484 /如何訪問這個正確的回調內部) – Bergi

回答

6

這是因爲成功的回調有不同的範圍,this沒有指向你的看法。
要快速解決這個問題,只是做一個參考this,並用它來代替:

var self = this; 
commentItem.save({'model':item}, { 
    success: function(receivedItem, response) { 
     self.addOne(receivedItem); // works 
    } 
}); 

,或者您可以使用下劃線的bind方法,結合不同的上下文中的函數:

success : _.bind(function(receivedItem, response) { 
    this.addOne(receivedItem); 
}, this) 
+0

你是天才的人!有用!它會對別人有用 - 我花了幾個小時來解決這個問題(我還沒有很好的JavaScript):) – Gediminas

+0

很好的答案,但我很好奇,爲什麼這個工程? – MdaG

+0

@MdaG你是指下劃線的'bind'方法嗎? –

0

這可能是一個遲到的答案。但會幫助正在尋找它的人。這是從setTimeout的回調訪問「這個」關鍵詞

CommentsListView = Backbone.View.extend({ 
... 
    addOne: function (item) { 
     // DO Stuff 
    }, 
    addNewComment: _.bind(function (event) { 
     setTimeout(_.bind(function(){ 
      this.addOne(/*receivedItem*/); 
     }, this), 1000); 
    }, this) 
});