2013-02-18 18 views
1

爲什麼這個日誌記錄爲窗口而不是Backbone對象?而不是這個窗口的主幹範圍

App.Models.Site = Backbone.Model.extend({ 
    url: 'assets/json/app.json', 

    initialize: function(){ 
     this.fetch({success:this.success}); 
    }, 

    success: function(){ 
     console.log('success', this.attributes); // log's: success undefined 
     console.log(this); // window 
    } 
}); 
+0

通常情況下,你可以通過上下文作爲參數:HTTP:// backbonejs。 org /#FAQ - 這個,但不在'this' :)情況下。 – WiredPrairie 2013-02-18 13:14:31

回答

2

由於該功能是通過jQuery的(或lib中所使用的任何DOM)ajax函數調用。

使用this.fetch({success:_.bind(this.success, this)});

+1

不完全是,Backbone在你和jQuery之間放置了一個成功處理程序,成功處理程序調用傳遞給'fetch',因此骨幹特定參數:[「接受選項哈希中的成功和錯誤回調,響應,選項)'和'(model,xhr,options)'分別作爲參數。「](http://backbonejs.org/#Model-fetch)。 – 2013-02-18 18:26:09

+0

@ muistooshort謝謝,我只是在猜測。 – Prinzhorn 2013-02-18 19:32:33

0

因爲你需要在你的初始化函數綁定this這樣的:

App.Models.Site = Backbone.Model.extend({ 
    url: 'assets/json/app.json', 

    initialize: function(){ 
     _.bindAll(this, 'success'); // Ensure the 'success' method has the correct 'this' 
     this.fetch({success:this.success}); 
    }, 

    success: function(){ 
     console.log('success', this.attributes); 
     console.log(this); // this is now correctly set 
    } 
}); 
0

「這個」,在成功中的抓取功能是不是在你的骨幹視圖範圍內的了屬性。一種解決方法是增加一個

var that = this; 

並使用「」在你成功獲取屬性象下面這樣:

var that = this; 
this.fetch({success: that.success}); 
相關問題