【发布时间】:2014-11-20 13:49:08
【问题描述】:
问题跳到底部
JQuery 插件:
$.fn.myPlugin = function( options ) {
var options = $.extend({
myOption: true,
edit: function() {},
done: function() {}
}, options);
options.edit.call(this);
options.done.call(this);
//plugin guts removed to prevent over complication
return {
edit: function(obj) {
$(obj).closest('#myParent').find('#myInput').autosizeInput(); //plugin to autosize an input
},
done: function(obj) {
$(this).closest('tr').find('td').not('.not').each(function(i) {
//do some things
});
}
}
});
请记住,这是我插件的精简版。
从页面调用:
$(document).ready(function() {
var myPlugin = $('.editable').myPlugin({
edit: $(this).on('click', '.edit-td', function(e) {
e.preventDefault();
//do some page specific stuff
myPlugin.edit( $(this) ); //call the edit returned function
}),
done: $(this).on('click', '.done-td', function(e) {
e.preventDefault();
//do some page specific stuff
myPlugin.done( $(this) ); //call the done returned function
});
});
});
这在大多数情况下都很好用,但是,我真正想要的是每次触发特定回调时都从我的插件内部调用函数 - 无需从插件外部调用。
我尝试在我的插件中包含委托事件:
$(this).on('click', '.edit-td', function(e) {
e.preventDefault();
$(this).closest('#myParent').find('#myInput').autosizeInput();
});
$(this).on('click', '.done-td', function(e) {
e.preventDefault();
$(this).closest('tr').find('td').not('.not').each(function(i) {
//do some things
});
});
但是当.edit-td 被触发时,它会传播并触发.done-td 事件,如果我将e.stopPropagation() 放入edit-td 函数中(因为它已被委托)edit-td 将完全停止触发。
和非委托方法:
$(this).find('.done-td').click(function(e, this) {});
但是在内部函数完成之前,我无法将返回的对象 (this) 解析为内部函数。 (只是出现未定义或missing formal parameter)。
*跳到这里
为了避免问题本地化 -
我需要从我的内部调用函数 每次触发特定回调时的插件。 不使用闭包调用它
类似:
if( $.fn.myPlugin.callback().is('edit') ) {
//fire function
}
【问题讨论】:
-
这是一个有趣的阅读,实际上是解决我的问题的原因。请提供这个作为答案,我会接受。颤抖。
-
当我读到这个问题时,我以为你不知道回调,这就是我评论链接的原因。如果你得到了答案,你可以关闭问题或保留它以获得更好的答案。我不太清楚你想要完成什么。
-
好的,我会关门的。
标签: javascript jquery jquery-plugins closures jquery-events