melanke / Watch.JS

watch the changes of any object or attribute

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Multiple watches to same object - unwatch only one

Jmales opened this issue · comments

I have a global value which is watched in multiple controllers. When one of them is closed I want to unwatch only the watcher within that controller.

However, if I use unwatch() function every watch associated with that object is being deleted and the watches in my other controllers stop working.

How can I work around this?

Have you tried passing the same callback as parameter?
http://jsfiddle.net/wu0d1wbd/

var obj = {
    phrase: "hey",
    name: "buddy",
    alert: function(){
        alert(obj.phrase + " " + obj.name);
    },
    alert2: function(){
        alert(obj.name + ", " + obj.phrase);
    }
}
    
watch(obj, "name", obj.alert);
watch(obj, "name", obj.alert2);

obj.name = "johnny";

setTimeout(function() {
    unwatch(obj, "name", obj.alert);
    obj.name = "phil";
}, 500);