我有一个插件定义如下:
(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中的原始元素似乎不起作用。正确的方法是什么?
谢谢。
发布于 2012-04-21 02:38:24
这个解决方案使用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...
}
});https://stackoverflow.com/questions/10251327
复制相似问题