通过JavaScript文档,我在JavaScript对象上发现以下两个函数看起来很有趣:
.watch
- 手表要分配一个值并在发生时运行一个函数。
.unwatch
- 使用手表方法删除设置的观察点。
更新:折旧警告
请勿使用 Watch()
和 untatch()
!这两个
方法仅在版本 58
之前在 firefox 中实现,它们是
在 firefox 58+
中删除并删除
用法
o = { p: 1 };
o.watch("p", function (id,oldval,newval) {
console.log("o." + id + " changed from " + oldval + " to " + newval)
return newval;
});
在 firefox
o.p = 2; //logs: "o.p changed from 1 to 2"
58+
示例 过去几年,从未使用过这些功能。
有人可以扔一些好的用例,这些功能会派上用场吗?
Going through Javascript documentation, I found the following two functions on a Javascript object looks interesting:
.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.
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;
});
Whenever we change the property value of "p", this function gets triggered.
o.p = 2; //logs: "o.p changed from 1 to 2"
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?
发布评论
评论(9)
现在是2018年,这个问题的答案有点过时:
今天,您现在可以使用对象要监视对象进行的更改。它是为OP试图做的目的而建立的。这是一个基本示例:
代理
对象的唯一缺点是:代理
对象在较旧的浏览器(例如IE11)和 polyfill 无法完全复制代理
函数。date
)的预期行为 -代理
对象最好与普通对象或数组配对。如果您需要观察对嵌套对象进行的更改,则需要使用 可观察的纤细 (我撰写了)。它是这样的工作:
It's now 2018 and the answers to this question are a bit outdated:
Today, you can now use the Proxy object to monitor (and intercept) changes made to an object. It is purpose built for what the OP is trying to do. Here's a basic example:
The only drawbacks of the
Proxy
object are:Proxy
object is not available in older browsers (such as IE11) and the polyfill cannot fully replicateProxy
functionality.Date
) -- theProxy
object is best paired with plain Objects or Arrays.If you need to observe changes made to a nested object, then you need to use a specialized library such as Observable Slim (which I authored). It works like this:
手表的真正设计是验证属性值。例如,您可以验证某物是一个整数:
您可以使用它来验证字符串长度:
但是,这些仅在Spidermonkey JavaScript引擎的最新版本中可用。如果您使用Jaxer或Jaxer或嵌入SpidermonKey引擎,但浏览器中尚未真正可用(除非您使用的是FF3)。
What watch is really designed for is validation of property values. For example you could validate that something is an integer:
You could use it to validate string length:
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).
查看
Object.prototype.\__defineGetter__
(or\ __定义__
)查看此功能在哪里。Object.defineProperty
现在应在所有当代浏览器中可用。Check out
Object.defineProperty
andObject.prototype.\__defineGetter__
(or\__defineSetter__
) to see where this functionality is heading.Object.defineProperty
should be available in all contemporary browsers real soon now.这是一种简单的替代方法,可以使用Getter/setter观看/UNDATCH字面的对象。每当更改
p
属性时,都可以调用任何函数。Here's a simple alternative to watch/unwatch for an object literal using just a getter/setter. Whenever the
p
property is changed, any function can be called.您可以看一下 javascript Prepery Events 库。这是我最近制作的一些事件呼叫者的小型库。它在[event] 属性上添加了一些
,这些属性可以像[event]
html-objects上的上的一样。它还具有简单的类型检查,如果失败,该检查将调用
onerror
事件。采用您的代码会导致这样的事情:
You could take a look at the Javascript Propery Events library. It's a small library extending
Object.defineProperty
with some event callers, that I made recently. It adds a fewon[event]
properties that can be used like theon[event]
properties of HTML-Objects. It also has a simple type check, which calls theonerror
event if it fails.Taking your code it would result in something like this:
=“ https://developer.mozilla.org/en-us/docs/web/javascript/Reference/global_objects/promise/promise” rel =“ nofollow noreferrer”> Promise> Promise>
Promise>在目标浏览器中支持的
很重要:
1)注意使用Promise时的异步行为。
2)object.defineProperty不会触发回调,只有分配操作员'='dim
Object.defineProperty
Promise
remove Promise and keep callback only if Promise is not supported in your target browser
Important:
1) Be aware of async behaviour on using promise.
2) Object.defineProperty doesn't trigger the callback, only assign operator '=' does
而不是使用代理,因此不是直接在原始对象上“聆听”,而是可以使用这样的东西:
该方法或多或少是在ReactJ中工作的方式,而是在此示例中具有源对象< strong> obj.state 和setter obj.setstate
您不必像我一样将两个都放在一个对象中,但似乎是组织事物的好方法
Instead of using Proxy and therefore not "listening" directly on the original object you can use something like this:
That approach is more or less how it would work in ReactJS, you have source object in this example obj.state and setter obj.setState
You don't have to put both in one object like I did but seems like a good way to organize things
据我所知,没有答案与OP的问题有关:
我的用例:想象一下现有库中的一个对象,该对象在实例化中接收
options
-Object,在创建后也可以使用。这些配置值中的某些可以在该对象的生命周期内更改,并且下次调用特定方法时,这些值将使用这些新的配置值。但是,现在我找到了只有在实例化期间提供的效果的选项,即b/c会注册某些事件听众 - 更改后更新值,但不会改变行为。但是我确实需要在运行时打开或关闭此行为。为了参数,让我们调用该选项
dosomethingonkeydown
。如何向不会改变API的该库中添加拉动请求?
我构建
”现在,任何人都可以在运行时更改对象上的此选项,即
myinstance.options.options.dosomethingonkeydown = false
,它将相应地更新其行为 - 并且对象的API保持不变。As far as i can read, no answer relates to the OP's question:
My use case: Imagine an object in an existing library that receives an
options
-object on instantiation, which is also available after it was created. Some of these config values can be altered during lifetime of that object, and on calling specific methods the next time, those will use these new config values.However, now i have found an option that only has an effect if supplied during instantiation, i.e. b/c it will register certain event listeners – changing it afterwards updates the value but doesn't change the behavior. But i really need to turn this behavior on or off during runtime. Lets call that option
doSomethingOnKeyDown
for the sake of the argument.How can i add a pull request to that library that doesn't fundamentally change the API?
I build a proxy:
Et voilá: now anyone can change this option on the object during runtime, i.e.
myInstance.options.doSomethingOnKeyDown = false
and it will update its behavior accordingly – and the API of the object stays the same.您可以使用setInterval
You can use setInterval