如何观察JS变量中的值变化 [英] How to observe value changes in JS variables

查看:150
本文介绍了如何观察JS变量中的值变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以帮助我做一些我认为相当直接的事情:

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();

这是我以后的基本想法,但我真正想要的是实际拥有onChange(in这个例子)是不同的,所以实际变量的新函数(而不是标准原型扩展),即:

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!

推荐答案

我可能不想尝试将方法添加到现有类型,而是创建一个可以包装主要类型的对象。我会称之为观察一个值,并可能实现如下:

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);
        }   
    };
}

然后可以用它来观察任何值的变化(只要然后只能通过可观察类上的方法更改值 - 一个小的减法IMO。

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);

这里的实例 - > http://jsfiddle.net/MeAhz/

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

这篇关于如何观察JS变量中的值变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆