新手问题 MessageBus 如何避免重复 subscribe?

dongli1985 · September 05, 2015 · Last by stephen replied at September 30, 2015 · 1902 hits

在使用中发现存在重复subscribe某频道的情况,如刷新当前页。我的 CoffeeScript 脚本如下:

$(document).on 'page:change', ->
  if /\/users\/\d+/.test(location)
    $('[id|=message-bus-collection]').each ->
      if not typeIsArray window.collection_channels
        window.collection_channels = []
      channel = $(this).attr('id').replace('message-bus-collection-', '/')
      window.collection_channels.push channel
      MessageBus.subscribe channel, (data) ->
        alert "check"              # <------------------ 这个alert显示该回调函数被重复调用。
        $("i##{data.collectable_type}-#{data.collectable_id}").show()
  else if typeIsArray window.collection_channels
    MessageBus.unsubscribe channel for channel in window.collection_channels

我觉得应该是检查当前的 client 是否已经订阅,但是不知道怎么做。MessageBus 的文档惜字如金,源程序暂时看不大明白,请教有经验的朋友,十分感谢!

楼主解决了吗?

You need to Sign in before reply, if you don't have an account, please Sign up first.