jQuery插件:调用其他插件方法的插件方法?

时间:2012-04-20 18:12:02

标签: javascript jquery

我有一个插件定义如此:

(function( $ ){
    var mymethods = {
        init: function(opts) {
            // do some wild awesome magic
            if (opts.drawtablefirst) $(this).drawtable(); // This doesn't actually work of course
        },

        drawtable: function() {
            $(this).empty().append($("<table>")); // Empty table, I know...
        }
    }

    // Trackman table
    $.fn.myplugin = function(method) {

        if (mymethods[method] ) {
            return mymethods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method ) {
            return mymethods.init.apply(this, arguments);
        }
    }
})( jQuery );

我希望能够从drawtable方法调用init方法,但这种方法无效。我实例化我的插件主要是:

$("div#container").myplugin({drawtablefirst: true})

但有时我不想传递drawtablefirst然后再手动调用它,例如:

$("div#container").myplugin('drawtable')

配置这个的最佳方法是什么drawtable是一个可访问的插件方法,但也可以从插件方法本身调用,例如init

此外,通过drawtable访问$(this)中的原始元素似乎不起作用。那里有什么合适的方法?

感谢。

1 个答案:

答案 0 :(得分:0)

此解决方案使用jQuery-ui 1.7+ .widget功能,这里是excellent link to what you get for free

$.widget("notUi.myPlugin",{
 options:{
   drawtablefirst:true,
   //...any other opts you want
 },
 _create:function(){
  // do some wild awesome magic
  if (this.options.drawtablefirst){
   this.drawtable(); // This actually works now of course
  } 
 },
 //any function you do not put an underscore in front of can be called via .myPlugin("name", //args)
 drawtable: function() {
   this.element.empty().append($("<table>")); // Empty table, I know...
 }
});
相关问题