【发布时间】:2011-09-12 13:39:50
【问题描述】:
我正在为如何最好地结合 javascript 类和 jQuery 插件而苦苦挣扎。这个问题不是很具体,我希望的是指向更多资源的指针。
基本上,我想将状态数据和私有方法存储在一个类中,然后扩展我调用插件的每个 jQuery 对象以具有这些私有方法和属性。这样我就可以在插件内部直接调用 jQuery 对象的方法。
我阅读了jQuery plugin design pattern (common practice?) for dealing with private functions,特别是大卫的回答,但是这每次都会初始化一个新的类,因此不能用于保存对象的状态。
我还找到了http://fuelyourcoding.com/jquery-plugin-design-patterns-part-i/,它建议创建一个类,然后将其存储在 .data() 中。
我认为理想情况下我想要的代码看起来像
(function( $ ){
var methods = {
init : function( options ) { // Initialize each object with a state and private methods },
show : function( ) {
// testFoo() is a private method that checks the element's state
if(this.testFoo()){
// Relying on jQuery's html() method
this.html() = this.fooTemplate();
}
}
};
// Boiler plate plugin from http://docs.jquery.com/Plugins/Authoring
$.fn.myPlugin = function( method ) {
// Method calling logic
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.myPlugin' );
}
};
})( jQuery );
最后,我似乎无法将私有方法直接烘焙到插件中,因为像“testFoo()”这样的方法将返回一个布尔值,因此不可链接。
想法?我以正确的方式接近这个吗?我应该使用另一种设计模式吗?也许根本不使用 jQuery 插件架构?
【问题讨论】:
-
+1 有趣的问题...您基本上希望能够做到
$('div').myPlugin(methods.show);?并扩展那些特定的 jQuery 对象......所以你可以做$('div').show()?我接近了吗?
标签: javascript jquery jquery-plugins