Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

javascript - How to observe value changes in JS variables

Im wondering if someone might be able to help me with something that i think it fairly straight forward:

Essentially i want to extend the prototypes of all datatypes (including intrinsic types), to allow some kind of custom functions, consider:

var x = "some string";
var y = 101;

x = "some other value";
y++;

x.onChange();
y.onChange();

This is the basic idea im after, but really what i want is to actually have the onChange (in this example) to be different so a new function for the actual variable (rather than a stardard prototype extension), ie:

x.onChange = function() {
    alert("x.onChange");
}

y.onChange = function() {
    alert("y.onChange");
}

This doesnt seem to work but i must be missing something quite simple no? I mean surely i can extend all object and types and add on new functions... no?

Any help would be greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I might be tempted to approach this not by trying to add methods to existing types, but to create an object that can wrap a primative type. I would call this "observing" a value, and might implement it something like this:

function observable(v){
    this.value = v;

    this.valueChangedCallback = null;

    this.setValue = function(v){
        if(this.value != v){
            this.value = v;
            this.raiseChangedEvent(v);
        }
    };

    this.getValue = function(){
        return this.value;
    };

    this.onChange = function(callback){
        this.valueChangedCallback = callback;
    };

    this.raiseChangedEvent = function(v){
        if(this.valueChangedCallback){
             this.valueChangedCallback(v);
        }   
    };
}

This can then be used to observe changes in any value (so long as that value is then changed only by methods on the observable class - a small detraction IMO).

Something like this would work with the above code:

var obs = new observable(123);
obs.onChange(function(v){
         alert("value changed to: " + v);
     });

// the onChange callback would be called after something like obs.setValue(456);

Live example here --> http://jsfiddle.net/MeAhz/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...