Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript property change event

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.

like image 582
joshontheweb Avatar asked Nov 12 '10 22:11

joshontheweb


1 Answers

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
like image 97
Guilherme Ferreira Avatar answered Sep 16 '22 16:09

Guilherme Ferreira