成功fetch
triggers a "change"
event:
取model.fetch([options])
[...]答"change"
事件將如果服務器的狀態下,從當前屬性不同觸發。
因此,如果fetch
做任何事情,都會有一個"change"
,你可以傾聽:如果this.currentUser
以其他方式改變
myApp.on("initialize:before", function() {
this.currentUser = new UserModel();
this.currentUser.on('change', function() {
myApp.vent.trigger('currentUser');
});
this.currentUser.fetch();
});
這也將引發"currentUser"
事件以及可能或可能不是你想要的。如果你只想要你的函數調用一次,那麼你當前的處理函數可能是最簡單的事情;你仍然可以使用on
和取消綁定處理程序時,它被稱爲:
myApp.on("initialize:before", function() {
var triggerCurrentUser = _.bind(function() {
myApp.vent.trigger('currentUser');
this.currentUser.off('change', triggerCurrentUser);
}, this);
this.currentUser = new UserModel();
this.currentUser.on('change', triggerCurrentUser);
this.currentUser.fetch();
});
你也可以使用_.once
但會留下一個空操作回調函數踢四周,也沒有必要。
其實我希望我的函數在模型被提取時調用一次,而不是在它改變時調用。所以在這一點上,使用'off'有什麼好處呢?比使用回調更值得推薦嗎? –
@LorraineBernard:如果您只想要一次性回調,您當前的「成功」處理程序沒問題。如果你想要多個通知,或者如果'this.currentUser.on()'和'this.currentUser.fetch()'在源代碼中的不同位置,你通常只使用'on'(即使用'success' wouldn由於狀態信息在其他地方而不起作用)。 –