fffixed/vue-bus

Memory Leak

blvz opened this issue ยท 3 comments

blvz commented

for (var name in $bus) bus.$off(name, $bus[name].bind(this))

Example: https://jsfiddle.net/1zz9snkv/

Jesus! You're really right bro! It's my big mistake!

blvz commented

No problem, mate. ๐Ÿ˜‰
I did a implementation myself, if you wanna copy it:

Vue.mixin({
  created () {
    if (!this.$options.$bus) return
    this.$busListeners = { }

    Object.keys(this.$options.$bus).forEach(name => {
      if (typeof this.$options.$bus[name] !== 'function') {
        throw new Error(name + ' is not a function.')
      }

      const fn = this.$options.$bus[name].bind(this)
      this.$busListeners[name] = fn
      bus.$on(name, fn)
    })
  },

  beforeDestroy () {
    if (!this.$options.$bus) return

    Object.keys(this.$options.$bus).forEach(name => {
      const fn = this.$busListeners[name]
      bus.$off(name, fn)
    })

    delete this.$busListeners
  }
})

EDIT: oops, updated the above. I think it's better to store the listeners in a separate, $busListeners object, to avoid conflicts with component's events.

Tnx, Rafael, I fixed it ๐Ÿ‘