2012-04-20 178 views
1

我有一个插件definedlike这样: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); 

我希望能够从init方法调用drawtable的方法,但这种方法是行不通的。我实例化我的插件大多喜欢:

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

但有时我不想通过drawtablefirst再后来手动调用它,如:

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

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

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

谢谢。

回答

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... 
} 
}); 
+0

哦,窗口小部件比UI插件更性感。我会看一看... – Wells 2012-04-20 18:43:41