2012-04-01 83 views
0

我有一個Backbone集合。我正在使用fetch將Facebook帖子延遲加載到初始化模型中。BeforeSend傳遞給Backbone的Fetch不允許觸發事件

https://gist.github.com/2271437

exports.Collection = class Posts extends Backbone.Collection 
    initialize: (models, options) => 
    @id = options.id 
    @activeDetails = false 
    @on "loadDetails", @loadDetails 
    @on "detailsLoaded", @logger 
    debug "initialized posts" 
    @fetch 
     beforeSend:() => 
     console.log "about to fetch..." 
     @trigger "postsLoading" 
     success: (collection, response) => 
     debug "successfully loaded ajax" 
     @trigger "postsLoaded" 
     error: (collection, response) => @trigger "postsLoadingError" 

一些奇怪的原因,當我嘗試觸發使用beforeSend處理事件,事件不會觸發。我可以調用任何函數,但是如果有任何函數嘗試使用@trigger "eventName",則事件從不以我能夠觀察的方式觸發。在上面的例子中,console.log函數工作得很好,但觸發器失敗。

任何想法?成功和錯誤處理程序工作出色。

回答

2

您在initialize方法內調用fetch,因此在觸發事件之前沒有機會綁定到該集合。 initialize方法在創建集合的實例時調用,這意味着您在構造函數返回之前調用fetch,但在綁定到它的事件之前需要集合的實例。

考慮的東西,看起來更像是這樣的:

class Posts extends Backbone.Collection 
    do_things: -> 
    @fetch 
     beforeSend:() => 
     console.log "about to fetch..." 
     @trigger "postsLoading" 
     success: (collection, response) => 
     debug "successfully loaded ajax" 
     @trigger "postsLoaded" 
     error: (collection, response) => @trigger "postsLoadingError" 

然後,如果你這樣做:

p = new Posts 
p.on('postsLoading', -> console.log('loading'))  
p.do_things() 

,你會看到你的postsLoading事件確實引發。

演示:http://jsfiddle.net/ambiguous/PDeFg/

這個故事的寓意很簡單:

不要叫fetch你的構造函數裏面,如果你關心的事件偵聽器。

+0

我愛你。 我可以setTimeout對象中的另一個函數來獲取之前等待滴答,並仍然有獲取對象初始化時的好處嗎? – RandallB 2012-04-01 20:49:32

+0

@RandallB:只要調用者在實例化集合(並且你可能想要記錄這種行爲)之後綁定它們的事件處理程序,''initialize''中的舊'setTimeout(...,0)'技巧應該工作。 – 2012-04-01 21:20:13

相關問題