【发布时间】:2012-01-07 17:00:09
【问题描述】:
我正在为 jQuery 插件开发一种全能的基本框架。我的结构基于找到 here 的 jQuery Plugins/Authoring 示例。
这是我正在构建的结构的进一步简化版本:
(function( $ ){
var methods = {
init : function( options ) {
var defaults = {
// place default settings for plugin here
}
var options = $.extend(defaults, options);
return this.each(function(){
var $this = $(this),
data = $this.data('PLUGINNAME');
if ( ! data ) {
// do more setup stuff here
}
});
},
destroy : function( ) {
return this.each(function(){
// do stuff to destroy any function binding
})
},
update : function( content ) {
return this.each(function() {
//do your update stuff here
})
}
};
$.fn.PLUGINNAME = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.PLUGINNAME' );
}
};
})( jQuery );
我现在想弄清楚的是如何向插件调用添加回调函数。我知道我需要另一个这样的参数:
$.fn.PLUGINNAME = function( method, callback ) {
但我不确定如何根据我目前拥有的内容来实现它。
【问题讨论】:
-
这个回调应该做什么以及它的签名是什么?
-
回调应该做什么并不重要。也许它只是一个函数,需要等到插件运行一些脚本(如 getJSON 调用)才能处理页面上的某些元素。
标签: javascript jquery plugins jquery-plugins methods