Simple utility to be able to attach listeners to events that fired when an object property changes
Basically using this utility on any plain object will create a new object that is an instance of a dispatcher and that will fire events when the "observed" properties change.
npm i --save object-change
objChange( obj:Object, properties:Array ):dispatcher
- obj:Object: The object with the initial values for the proxy instance.
- properties:Array: The properties that will trigger the change event when its values change.
Returns An instance of a dispatcher that fire:
changeevent whenever any observed property changes.
change:NAME_OF_PROPevent whenever the observed property
var obj =someProp: '1'anotherProp: 2;var objChange = ;var proxyObj = ;proxyObj;proxyObjsomeProp = 'some other value';// ==> output <==// change from: 1 to: 'some other value';proxyObjanotherProp = 1// doesn't fire change because is not observed.
Important notes and limitations
- The events fire synchronously. So far I haven't had any problems. Make sure you don't do expensive tasks inside the
- The dispatcher instance returned have the following methods:
on. To add a listener to an event in the dispatcher
fire. To fire an event on the event dispatcher
off. To remove the listeners The events works similarly to the jQuery
fireis similar to
- Be aware that the properties should not be named
- It does not work on nested properties. This is by design, I just wanted to keep it simple.
- The base object is used as the prototype for the returned object. If you change a nested property, it will affect the original object I did it this way to avoid having to copy all the properties to the new object, but... I might consider change it in the future if it is proven to be a problem.