5

In directive bind method, there is a vnode.context.$watchand every time that directive added to HTML, it is also adding another watcher with previous watcher. Because of that same watchers are calling more than once.

Is there any way to destroy the previous watcher when directive unbind method called.

Vue.directive("dynamic-lookup", {
    bind: function (el, binding, vnode) {        
        let dependency = setValue("dynamic-lookup-dependency");       
        if (dependency) {
            vnode.context.$watch(dependency, function (newVal, oldVal) { }); });
        }
    },
    unbind: function(el, binding, vnode) {
        console.log("unbind");
    }
});
Anik Saha
  • 4,313
  • 2
  • 26
  • 41

2 Answers2

3

According to the documentation, the $watch function it-self returns the unwatch function. You can save the returned function in vnode.context and call this function in directive unbind hook like this:

Vue.directive("dynamic-lookup", {
    bind: function (el, binding, vnode) {
        let unwatch = vnode.context.$watch(vnode.context.property, function (newVal, oldVal) { 
                //Do something
            }); 
        });
        if(!vnode.context['unwatch'])
            vnode.context['unwatch'] = unwatch;
    },
    unbind: function(el, binding, vnode) {
        vnode.context.unwatch();
    }
});
tony19
  • 125,647
  • 18
  • 229
  • 307
ATT
  • 337
  • 3
  • 10
0

I think you can unwatch your dependency when you want.

Documentation vm.$watch returns an unwatch function that stops firing the callback: https://v2.vuejs.org/v2/api/#vm-watch

var unwatch = vnode.context.$watch(dependency, function (newVal, oldVal) {
});
// later, teardown the watcher
unwatch()
tony19
  • 125,647
  • 18
  • 229
  • 307
Shim-Sao
  • 2,026
  • 2
  • 18
  • 23