jQuery custom events on non-DOM objects

雨燕双飞 提交于 2019-12-06 19:14:16

问题


I read some code recently that does something like this:

bob = {'name': 'Bob Smith', 'rank': 7};
$(bob).bind("nameChanged", function () { /* ... */});
// ...
$(bob).trigger("nameChanged");

This appears to work.

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?

If you wanted to use an event-driven model for your Model or View objects in JavaScript, how would you do it?


回答1:


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.



来源:https://stackoverflow.com/questions/5411228/jquery-custom-events-on-non-dom-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!