I need to fire an event every time a property is updated/changed in order to keep dom elements in sync with the property values on the model (Im using john resig's simple inheritance http://ejohn.org/blog/simple-javascript-inheritance/). Is this possible to do in a cross-browser way? It seems to me that if I could wrap whatever function js uses to set properties and make it fire an event, that it could work, Im just not sure how to do that.
Object defineProperty/defineProperties does the trick. Here goes a simple code. I have built some data binding frameworks based on that, and it can get really complex, but for exercising its like this:
var oScope = {
    $privateScope:{},
    notify:function(sPropertyPath){
        console.log(sPropertyPath,"changed");
    }
};
Object.defineProperties(oScope,{
    myPropertyA:{
        get:function(){
            return oScope.$privateScope.myPropertyA
        },
        set:function(oValue){
            oScope.$privateScope.myPropertyA = oValue;
            oScope.notify("myPropertyA");
        }
    }
});
oScope.myPropertyA = "Some Value";
//console will log: myPropertyA changed
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With