非DOM对象上的jQuery自定义事件 [英] jQuery custom events on non-DOM objects
问题描述
我最近读了一些类似的代码:
I read some code recently that does something like this:
bob = {'name': 'Bob Smith', 'rank': 7};
$(bob).bind("nameChanged", function () { /* ... */});
// ...
$(bob).trigger("nameChanged");
这似乎有用。
但是我在jQuery文档或源代码中找不到任何关于使用既不是选择器也不是DOM节点的对象调用jQuery构造函数的内容。所以我的问题是,这是一个受支持的用途,还是它本质上是偶然的?
But I can't find anything in the jQuery documentation or source about calling the jQuery constructor with an object that is neither a selector nor a DOM node. So my question is, is this a supported use, or is it essentially working by accident?
如果你想为你的Model或View对象使用一个事件驱动的模型在JavaScript中,你会怎么做?
If you wanted to use an event-driven model for your Model or View objects in JavaScript, how would you do it?
推荐答案
它发生的事情是它只是将该对象包装在jQuery包装器中。然后,它将回调应用于该对象上的新属性,然后触发它。
What happens is that it just wraps that object in a jQuery wrapper. It then applies a callback to a new property on that object and then triggers it.
这是一种奇怪的做事方式,但完全可以接受。
It's an odd way of doing things, but perfectly acceptable.
这篇关于非DOM对象上的jQuery自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!