我无法将自定义事件添加到jQuery插件。jQuery插件实例上的自定义事件触发器
我做了一个非常简单的jQuery插件从我触发一个事件,但是附加的处理程序不正确地触发:如果我用我的插件http://jsfiddle.net/FhqNf/2/
(function($) {
var my_plugin = function(link, opts) {
var $this = this, img, o={};
defaults = {
color: 'rgb(255, 0, 0)'
};
$.extend(this, $.fn, {
init : function() {
o = $.extend(defaults, opts);
link.on('click', $this.changeColor);
},
changeColor : function (e) {
if(link.css('color') == o.color)
link.css('color', 'blue');
else
link.css('color', o.color);
$this.triggerChange();
},
triggerChange : function() {
$this.triggerHandler('custom', {test: 'ok', color: o.color});
}
});
this.init();
};
$.fn.my_plugin = function(opts) {
return new my_plugin(this, opts);
};
然后和附加功能,我的“定制“事件处理程序,该事件不火:
var test1 = $('#test1').my_plugin();
test1.on('custom', function (data) { console.log(data); alert('test1') });
编辑:解决方法是将附加/‘链接’DOM对象触发事件,但我想触发连接到我的插件实例的事件。这不可能吗?
在此先感谢。
通过适当你是什么意思?我看到它的作品。 – boyd 2013-05-12 08:06:04
不,“自定义”事件处理程序永远不会被解雇,我已经更新了我的问题 – Laurent 2013-05-12 08:26:10