Fluidbyte
Fluidbyte

Reputation: 5210

Monitor changes on object property

Say I have an object similar to the following:

Cars = {
    "car_one": {
        data: {
            make: "Ford",
            model: "Festiva"
        },
        img: "car_one.jpg"
    },
    "car_two": {
        data: {
            make: "Chevy",
            model: "Pinto",
            color: "Green"
        },
        img: "car_two.jpg"
    }
    ...and so on...
}

I am hoping to find a way to monitor just the data property (and all sub-properties) for changes, then be able to setup a function to fire.

I have been looking at Object.watch() but testing seems to show that I would need to have it manually setup to check each property of Cars.{some_car}.data which (as shown in my example) isn't a constant set. I guess I'm hoping there's a less complex method that I'm just not aware of.

Upvotes: 2

Views: 1469

Answers (2)

plalx
plalx

Reputation: 43718

Unfortunately, as of today the easiest way would probably be to loop over the properties in data and call Object.watch for each of them. However, we might have Object.observe at the rescue eventually. If you are looking for a cross-browser Obect.watch implementation, have a look here.

Other alternatives would be to wrap your data in an observable object that allows to modify the data through a generic set method that would fire events when some properties are modified or to have some property watching task that would execute at a specific interval or triggered by specific actions that would check the object for changes. However, these alternatives are not any simpler.

Upvotes: 1

Ben McCormick
Ben McCormick

Reputation: 25728

Depending on how much control you have over how its called, you could make an accessor function. The function could take an object as an argument, and set that object as the current value if the argument is set. For your use you can add a trigger of some type here. If no argument is passed it would return the current value.

Thats the type of API that knockout uses to great effect.

In modern browsers, getters and setters make this easy. For older values you could have an accessing property and then another property that serves as the holder for the data.

Upvotes: 1

Related Questions