【发布时间】:2013-04-19 19:51:44
【问题描述】:
我正在使用一个样板插件设计,看起来像这样,
;(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。
现在我会像这样在这些 div 上调用我的 test 插件,
$(".container").test({
onSomething: function(){
}
});
现在,当从我的插件内部调用函数 onSomething 时,我如何调用引用实例 onSomething 函数的插件公共方法?
例如,first container div 发生了一些事情,而 onSomething 函数仅被调用 first container div。
为了更清楚一点,我尝试将 this 实例传递给 onSomething 函数,这样我就可以公开 all 插件数据,然后我可以执行类似的操作,
onSomething(instance){
instance.someMethod();
instance.init();
//or anything i want
}
在我看来,这看起来很不对劲,所以一定有更好的方法......还是没有?
【问题讨论】:
标签: javascript jquery jquery-plugins