2013-06-28 54 views
1

我目前正試圖編寫一個模型,只要數據被提取就運行一個函數。就我而言,我正在以正確的方式實施它,但它一再無法按我期望的方式工作。骨幹事件地圖不起作用

在分鐘,該模型是這樣的:

var MyModel = Backbone.Model.extend({ 
    // fetch the data for this, on return, create modela about it 
    url: function() { 
     return 'api.example.com/users/' + this.id + '/intialisation'; 
    }, 
    events: { 
     reset: alert('this works') 
    }, 
    makeItems: function() { 
     var newItems, currentInitialiser, currentItem; 

     alert('this does not'); 
    } 
}); 

每當fetch()叫上了這樣一個實例,警告框彈出「這個工程」預期。但是,如果我改變事件地圖

events: { 
    reset: "makeItems" 
} 

events: { 
    reset: this.makeItems 
} 

功能不運行(你看不到的「這行不通」的提示框)。也許這是由於我對這個事件地圖的工作方式的誤解,但我很確定我看到過這樣的東西已經工作,我不明白爲什麼這不會。我已經看過骨幹文檔,但他們不是非常具有描述性,但據我瞭解,我寫的內容應該可行。

希望這不會太棘手難以理清

非常感謝。

回答

1

通常,事件散列用於骨幹視圖,如骨幹的documentation所支持。對於模型,您希望使用listenTo創建偵聽器。

var MyModel = Backbone.Model.extend({ 
    // fetch the data for this, on return, create modela about it 
    url: function() { 
     return 'api.example.com/users/' + this.id + '/intialisation'; 
    }, 
    initialize: function() { 
     this.listenTo(this,'reset',this.makeItems); 
    }, 
    makeItems: function() { 
     var newItems, currentInitialiser, currentItem; 
     alert('this does not'); 
    } 
}); 

這應該指出你在正確的方向。

編輯:此外,根據Backbone的文檔,模型上的fetch不會觸發reset。它觸發一個changehttp://backbonejs.org/#Model-fetch

+0

'alert('這個作品')'怎麼會起作用? –

+0

這是一個非常好的問題。當我複製你的代碼時,它並不適用於我,除了當我實際定義MyModel時。然而,MyModel的實例不會觸發事件。 – damienc88

+0

我覺得我很愚蠢。我將括號放在'alert'的末尾,所以函數實際上被調用,結果被傳遞到地圖中。 –