使用“live”的 jQuery 插件模式
我有很多关于编写面向对象的 javascript 代码和开发 jQuery 插件的文章,到目前为止一切都很好,我了解它们是如何工作的,并且我可以创建自己的插件。
但是,所有文章都存在一个问题(即使有官方插件创作指南 - http://docs.jquery .com/Plugins/Authoring) - 这些所有模式都不支持“实时”。
让我们以这种模式为例 - http: //www.virgentech.com/blog/2009/10/building-object-driven-jquery-plugin.html
$.fn.myplugin = function(options)
{
return this.each(function()
{
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('myplugin')) return;
// pass options to plugin constructor
var myplugin = new MyPlugin(this, options);
// Store plugin object in this element's data
element.data('myplugin', myplugin);
});
};
将在每个 jQuery 匹配对象上创建新的“MyPlugin”实例。
如何更改它(如果可能)以便它可以在将来添加的元素上工作?
谢谢
I have red many articles about writing object oriented javascript code and developing jQuery plugin, so far so good, I understand how they work and I can create my own plugins.
But, there is one problem with all the articles ( even with official plugin authoring guide - http://docs.jquery.com/Plugins/Authoring ) - these all patterns don`t support "live".
Let`s take for example this pattern - http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html
$.fn.myplugin = function(options)
{
return this.each(function()
{
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('myplugin')) return;
// pass options to plugin constructor
var myplugin = new MyPlugin(this, options);
// Store plugin object in this element's data
element.data('myplugin', myplugin);
});
};
There will be created new "MyPlugin" instance on each jQuery matching object.
How to change it (if it`s posible) so it would work on elements that are added in the future?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我经常在我的插件中成功地使用 live 作为自定义选项。下面是一个向被单击的元素添加警报的简单示例:
在此示例中,任何可以与 $('...').live('click', ...') 正常工作的内容都可以与 $('.live('click', ...') 一起工作。 ..').clickAlert({live: true});
另外一件事,大多数插件设计都让你做这样的事情:
不幸的是,在
each
循环中使用 live 是行不通的。I’ve been using live with success in my plugins often as a custom option. Here's a trivial example that adds an alert to elements that are clicked:
In this example anything that would work normally with $('...').live('click', ...') will work with $('...').clickAlert({live: true});
One additional thing, most plugin designs have you do something like this:
Unfortunately, using live inside the
each
loop won't work.我发现这有效(jQuery 1.5.2):
I find this works (jQuery 1.5.2):