Javascript 对象中属性值更改的侦听器 [英] Listener for property value changes in a Javascript object

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

问题描述

浏览 Javascript 文档,我发现 Javascript 对象上的以下两个函数看起来很有趣:

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

.watch - 监视要为属性分配值并在发生时运行函数.
.unwatch - 删除使用 watch 方法设置的观察点.

.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.

更新:弃用警告
不要使用watch()unwatch()!这两个方法仅在 58 版本之前的 Firefox 中实现,它们是在 Firefox 中弃用和删除 58+

UPDATE: Deprecation warning
Do not use watch() and unwatch()! These two methods were implemented only in Firefox prior to version 58, they're deprecated and removed in Firefox 58+


示例用法:


Sample usage:

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 past few years and never used these functions.
Can someone please throw some good use cases where these functions will come in handy?

推荐答案

watch 的真正设计目的是验证属性值.例如,您可以验证某事物是整数:

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天全站免登陆