将事件传递给 jQuery 插件
我刚刚开始为 jQuery 编写插件。我找到了一个很好的教程,如何开始使用它,但我错过了一点。我想为每个元素注册一个独立的插件对象,并且我需要它们的事件。
这是我得到的代码:
(function($){
var MyPlugin = function(pElement, pOptions)
{
var element = $(pElement);
var object = pElement;
var settings = $.extend({
param: 'defaultValue'
}, pOptions || {});
this.onfocus = function() {
element.val('Focus');
};
this.onblur = function() {
element.val('Blur');
}
// DO I NEED THIS?
object.onfocus = this.onfocus;
object.onblur = this.onblur;
};
$.fn.myplugin = function(options)
{
return this.each(function()
{
var element = $(this);
if (element.data('myplugin')) { return };
var myplugin = new MyPlugin(this, options);
element.data('myplugin', myplugin);
});
};
})(jQuery);
我需要将公共方法“onfocus”和“onblur”从“this”复制到“object”吗?有更好的办法吗?
I just started writing Plugins for jQuery. I found a good tutorial how to start with it, but one point I missed. I want register a independent plugin-object for each element and I need them events.
Here the code I got atm:
(function($){
var MyPlugin = function(pElement, pOptions)
{
var element = $(pElement);
var object = pElement;
var settings = $.extend({
param: 'defaultValue'
}, pOptions || {});
this.onfocus = function() {
element.val('Focus');
};
this.onblur = function() {
element.val('Blur');
}
// DO I NEED THIS?
object.onfocus = this.onfocus;
object.onblur = this.onblur;
};
$.fn.myplugin = function(options)
{
return this.each(function()
{
var element = $(this);
if (element.data('myplugin')) { return };
var myplugin = new MyPlugin(this, options);
element.data('myplugin', myplugin);
});
};
})(jQuery);
Do I need to copy my public methods "onfocus" and "onblur" from "this" to "object"? Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编写 jQuery 插件的最佳指南可能是 jQuery 自己的。
jQuery 的事件系统 是插件处理事件的最佳方式。如果您使用 jQuery 1.7+(如果可能的话,我推荐使用它),
.on()
和.off()
是您的主力。您不仅可以绑定浏览器事件(例如 focus 和 blur),还可以创建完全自定义的事件(例如 'iamasuperstar')并使用this.trigger( 'iamasuperstar' 手动触发它们')
。所以你应该为你的插件做这样的事情:
element.on( 'focus', function() {} )
element.on( 'blur', function() {} )
...以及您需要的任何其他内容。
The best guide for writing jQuery plugins is probably jQuery's own.
jQuery's event system is the best way of handling events for your plugin. If you're using jQuery 1.7+ (which I recommend, if it's possible),
.on()
and.off()
are your workhorses. Not only can you bind browser events like focus and blur, you can create completely custom events like 'iamasuperstar' and trigger them manually withthis.trigger( 'iamasuperstar' )
.So you'd do something like this for your plugin:
element.on( 'focus', function() {} )
element.on( 'blur', function() {} )
...and whatever else you need.
为什么不:
Why not: