سؤال

I'm working on a very simple project, if it were larger I would use angular or backbone, or some other MVC library. In my case I just need to trigger a function whenever an array/object is changed. What's the simplest way to accomplish this?

هل كانت مفيدة؟

المحلول

here's a simple and efficient way to use a getter/setter to monitor object properties:

var myObj={a:1, b:2, c:3};

function watch(obj, prop, callBack){
   var x=obj[prop];
   Object.defineProperty(
      obj, prop, 
      {get:function(){return x;},
      set:function(n){ callBack(n,x); x=n; }
   }) ;
}

watch(myObj, "b", function(n,x){
   alert("was:"+x+", now " + n);
});

myObj.b=123; // shows: "was 2, now 123"

i have built a simple MVC upon this concept and mustache and it works very well.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top