JQuery Plugin - 通过回调触发内部函数

Posted

技术标签:

【中文标题】JQuery Plugin - 通过回调触发内部函数【英文标题】:JQuery Plugin - triggering internal functions by callback 【发布时间】: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

【问题讨论】:

learn.jquery.com/plugins/advanced-plugin-concepts 这是一个有趣的阅读,实际上是解决我的问题的原因。请提供这个作为答案,我会接受。颤抖。 当我读到这个问题时,我以为你不知道回调,这就是我评论链接的原因。如果你得到了答案,你可以关闭问题或保留它以获得更好的答案。我不太清楚你想要完成什么。 好的,我会关门的。 【参考方案1】:

我需要像这样返回一个函数:

return 
    enable: function(arg) 
        //do something
    ,
    disable: function(arg) 
        //do something
    

这样我就可以在我的插件内部通过这样引用它来调用它:

    this.myPlugin().disable();

【讨论】:

以上是关于JQuery Plugin - 通过回调触发内部函数的主要内容,如果未能解决你的问题,请参考以下文章

jQuery Validate Plugin - 触发单个字段的验证

JQuery源码分析

jQuery.getJSON 不会触发回调

[ jquery 效果 fadeToogle([speed,[easing],[fn]]) ] 此方法用于通过切换不透明度的变化来实现所有匹配元素的淡入效果,并在动画完成后可选地触发一个回调函数(代码

jQuery - .always() 回调触发太快

[ jquery 效果 fadeTo([speed,[easing],[fn]]) ] 此方法用于通过调整不透明度的变化至指定目标来实现所有匹配元素的淡入效果,并在动画完成后可选地触发一个回调函数(代