[英]jQuery plugin: plugin methods calling other plugin methods?
I have a plugin definedlike so: 我有一个像这样定义的插件:
(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 );
I want to be able to call the drawtable
method from the init
method, but that approach isn't working. 我希望能够从
init
方法中调用drawtable
方法,但是该方法不起作用。 I instantiate my plugin mostly like: 我实例化我的插件主要是这样的:
$("div#container").myplugin({drawtablefirst: true})
But sometimes I don't want to pass drawtablefirst
and then later call it manually, like: 但是有时候我不想先传递
drawtablefirst
,然后再手动调用它,例如:
$("div#container").myplugin('drawtable')
What is the best way to configure this so drawtable
is an accessible plugin method, but also can be called from within the plugin methods themselves such as init
? 配置此表的最佳方法是什么,所以
drawtable
是可访问的插件方法,但也可以从插件方法本身(如init
调用?
Also, accessing the original element in drawtable
via $(this)
doesn't seem to work. 另外,通过
$(this)
访问drawtable
的原始元素似乎不起作用。 What's the proper approach there? 那里的正确方法是什么?
Thanks. 谢谢。
this solution uses jQuery-ui 1.7+ .widget functionality, here's an excellent link to what you get for free 该解决方案使用jQuery-ui 1.7+ .widget功能,这是免费提供的绝佳链接
$.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...
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.