0

我有一个骨干系列。我习惯fetch在初始化时将 Facebook 帖子延迟加载到模型中。

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 函数工作得很好,但是触发器失败了。

有任何想法吗?成功和错误处理程序工作出色。

4

1 回答 1

2

您在方法fetch内部调用,initialize因此在触发事件之前没有任何机会绑定到该集合。在创建集合的实例时调用该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如果您关心事件侦听器,请不要在构造函数内部调用。

于 2012-04-01T07:56:49.697 回答