带有方法和回调的 jQuery 插件
我正在为 jQuery 插件开发一种万能的基本框架。我的结构基于此处找到的 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 ) {
但我不确定如何根据我目前拥有的参数来实现它。
I'm working on a kind of do-it-all basic framework for jQuery plugins. I'm basing the structure off of the jQuery Plugins/Authoring example found here.
Here's a further simplified version of the structure I'm building:
(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 );
The piece that I'm trying to figure out now is how to add a callback function to the plugin call. I know that I'll need another parameter like this:
$.fn.PLUGINNAME = function( method, callback ) {
but I'm not sure how to go about implementing that based on what I currently have.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要调用回调函数,可以使用.call方法。
在示例中,我传递了选项,但您可以传递任何您需要的内容。
To call the callback function, you can use the .call method.
In the example, I passed in options, but you can pass in whatever you need to.