i have an array of objects, and these objects all have an ‘isvalid’ attribute.
Is there a way with JQuery or plain javascript to bind code to the event that the value of that property changes?
So when i have an array with 10 objects, i want to execute a function when the ‘isvalid’ property of one of the object changes.
Is that possible?
Michel
It’s possible with plain JavaScript by using a property setter function. Using ES5 syntax, that looks like this (live example — works in Chrome and other browsers with reasonable ES5-compliance):
When the
t.foo = "bar";assignment is executed, the setter function is called. You can have the setter function call a callback if you like, to notify you that theThingobject was changed.Note that the above is just an example. It uses the
fooStorageproperty to store the value offoo, which is less than ideal but nice and simple for an example.To do this in a way that’s compatible with non-ES5 JavaScript engines, you either have to fall back on some proprietary and now-deprecated syntax from Mozilla (which won’t work on other engines), or just use an explicit setter function (live example):
(And again, this is just an example using a simplistic means of storing
foo‘s value.)This has the advantage that it works with just about any JavaScript engine, not just ES5-compliant ones, and it’s explicit that setting
foois a function call, not just a property assignment (whereas with the ES5 setter/getter syntax, the person setting thefooproperty doesn’t know that it’s a function call — which has upsides and downsides).So that’s how you capture the fact that the property changed. Then it’s just a matter of allowing callbacks to be registered and removed to receive notification of changes. These are easily managed in a simple array. Here’s an ES5-based example doing it on a per-object basis; obviously you could do this in some kind of grouped way instead for the entire array of objects you want to let people watch. (live copy)
To do that without an ES5 JavaScript engine, just set the
setFoo/getFoomodel described earlier, and make sure the engine supportsArray#indexOfcorrectly (some engines don’t have it at all, some use==rather than===equivalence) or replace the use ofArray#indexOfinremoveFooChangeHandlerwith a simple loop through the array looking for the callback:Side note: There are a number of anonymous functions in these examples. I’ve done that to avoid making things seem complex, but I’m not a fan of anonymous functions, I prefer that functions have names. See the link for details.