监听器在JavaScript对象属性值的变化 [英] Listener for property value changes in a javascript object

查看:193
本文介绍了监听器在JavaScript对象属性值的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经历的JavaScript文件,我发现了一个JavaScript对象以下两个功能看起来很有趣:

Going through javascript documentation, I found the following two functions on a javascript object looks interesting:

.watch - 手表的属性被分配一个值,当出现运行的函数结果。
.unwatch - 删除一个观察点的手表方法设置

.watch - Watches for a property to be assigned a value and runs a function when that occurs.
.unwatch - Removes a watchpoint set with the watch method.

使用范例:

o = { p: 1 };
o.watch("p", function (id,oldval,newval) {
    console.log("o." + id + " changed from " + oldval + " to " + newval)
    return newval;
});

每当我们改变P的属性值,该功能被触发。

Whenever we change the property value of "p",this function gets triggered.

o.p = 2;   //logs: "o.p changed from 1 to 2"

我的工作JavaScript来实现快速的几年里,从来没有使用这些功能。结果
可有一个人请抛出一些很好用的情况下,这些功能会派上用场?

I am working on javascript for the fast few years and never used these functions.
Can some one please throw some good use cases where these functions will come handy?

推荐答案

手表什么是真正专为是属性值的验证。例如,你可以验证的东西是一个整数:

What watch is really designed for is validation of property values. For example you could validate that something is an integer:

obj.watch('count', function(id, oldval, newval) {
    var val = parseInt(newval, 10);
    if(isNaN(val)) return oldval;
    return val;
});

您可以用它来验证字符串长度:

You could use it to validate string length:

obj.watch('name', function(id, oldval, newval) {
    return newval.substr(0, 20);
});

不过,这些都只是在SpiderMonkey的JavaScript引擎的最新版本。伟大的,如果你正在使用Jaxer的或嵌入SpiderMonkey的引擎,但在浏览器中没有真正可用的,但(除非你是使用FF3)。

However, these are only available in the latest versions of the SpiderMonkey javascript engine. Great if you are using Jaxer or embedding the SpiderMonkey engine, but not really available in your browser yet (unless you are using FF3).

这篇关于监听器在JavaScript对象属性值的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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