如果没有延迟初始化,回流触发器将无法工作

Reflux trigger won't work without a delay in init

我使用 Reflux,通常我会在发出 ajax 调用后触发,而且效果很好。出于测试目的,我不需要调用 ajax 并且我注意到触发器将无法工作,除非我给出一个最小 5 毫秒的超时。这是工作和不工作的例子。

无效示例: </p> <pre><code>window.threadStore = Reflux.createStore init: -> @state = @getInitialState() @fetchThreads() getInitialState: -> loaded: false threads: [] fetchThreads: -> # ajax call for not Testing, and just trigger for Testing @state.threads = FakeData.threads(20) @state.loaded = true @trigger(@state) # This will NOT work!

这将起作用: </p> <pre><code>window.threadStore = Reflux.createStore init: -> @state = @getInitialState() @fetchThreads() getInitialState: -> loaded: false threads: [] fetchThreads: -> # ajax call for not Testing, and just trigger for Testing @state.threads = FakeData.threads(20) @state.loaded = true setTimeout( => @trigger(@state) # This WILL work! , 500)

你能解释一下为什么它不能立即起作用吗?应该吗?是bug还是什么我不明白。

这是因为组件从 getInitialState 获取空数组并且它发生在调用 trigger 之后。

init 在创建商店实例时被调用,这意味着 fetchThreads 中的触发器在安装组件之前立即被调用。当稍后安装侦听组件时,它会从 getInitialState 上的存储中获取空数组。

我建议进行以下更改:

window.threadStore = Reflux.createStore
  init: ->
    @state =
      loaded: false
      threads: []
    @fetchThreads()
  getInitialState: ->
    @state # TODO: State should be cloned for sake of concurrency
  fetchThreads: ->
    # NOTE: Assign a new state for the sake of concurrency
    @state = 
      loaded: true
      threads: FakeData.threads(20)
    @trigger(@state) # This will SHOULD work now ;-)