我正在使用如下所示的样板插件设计,
;(function ( $, window, document, undefined ) {
var pluginName = "test",
defaults = {};
function test( element, options ) {
this.init();
}
test.prototype = {
init: function() {}
}
$.fn.test = function(opt) {
// slice arguments to leave only arguments after function name
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var item = $(this), instance = item.data('test');
if(!instance) {
// create plugin instance and save it in data
item.data('test', new test(this, opt));
} else {
// if instance already created call method
if(typeof opt === 'string') {
instance[opt].apply(instance, args);
}
}
});
};
})( jQuery, window, document );
现在说我有两个 <div>
同级container
.
现在我会调用我的 test
这些 div 上的插件就像这样,
$(".container").test({
onSomething: function(){
}
});
现在当函数 onSomething
从我的插件内部调用,我如何调用引用实例 onSomething
的插件公共(public)方法函数是从哪里调用的?
例如,第一个 container
发生了一些事情div 和 onSomething
仅第一次调用函数 container
分区。
为了让它更清楚一点,我尝试通过 this
实例到onSomething
函数,这样我就可以公开所有插件数据,然后我可以做类似的事情,
onSomething(instance){
instance.someMethod();
instance.init();
//or anything i want
}
对我来说,这看起来很错误,所以一定有更好的方法......或者没有?
最佳答案
嗯,我不确定这是否是最好的主意,但您可以将当前对象作为参数传递。比方说 onSomething : function(obj) { }
因此,每当插件调用“onSomething”时,您可以这样调用它:“onSomething(this)”,然后将该对象引用为
object`
让我们举一个具体的例子。
var plugin = function (opts) {
this.onSomething = opts.onSomething;
this.staticProperty = 'HELLO WORLD';
this.init = function() {
//Whatever and lets pretend you want your callback right here.
this.onSomething(this);
}
}
var test = new Plugin({onSomething: function(object) { alert(object.staticProperty) });
test.init(); // Alerts HELLO WORLD
希望这有帮助,如果还不够清楚请告诉我。
哦等等,这就是你所做的。
关于javascript - jQuery 从回调函数内部调用插件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16112514/