[英]JQuery Plugin - triggering internal functions by callback
跳到底部提問
$.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
}
我需要像這樣返回一個函數:
return {
enable: function(arg) {
//do something
},
disable: function(arg) {
//do something
}
}
這樣,我可以從插件內部調用它,方法是像這樣引用自身:
this.myPlugin().disable();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.