我有一个根据jQuery authoring guide编写的基本插件。此插件为ul
个元素(activate
,deactivate
和search
)实现了一些基本功能。
jquery.myplugin.core.js
(function($) {
var methods = {
init : function(opts){
var options = $.extend({}, $.fn.list.defaults, opts);
return this.each(function(i) {
...
methods.search("my search query"));
});
},
deactivate : function(){ ... },
activate : function(){ ... },
search : function(query){ ... },
};
$.fn.list = 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.list' );
}
};
$.fn.list.defaults = {...};
})(jQuery);
我的应用中有很多列表,每个列表执行不同的操作 - 一些共享功能。例如;两个列表可能被视为可删除,以便可以从中删除项目。有没有办法将这些额外的功能集编写为核心插件的mixins或扩展插件?
所以我会:
我看了Best Way to Extend a jQuery Plugin,这让我想到了:
jquery.myplugin.deletable.js
(function($) {
var extensionMethods = {
delete : function(elem){ console.log("deleting "+elem); }
};
$.fn.list.deletable = function(){ return $.extend(true, $.fn.list.prototype, extensionMethods); };
})(jQuery);
我认为可以让我这样做:
>>> $('#list').list.deletable();
>>> $('#list').list.deletable("delete", elem);
>>> $('#list').list.deleteable("search", "some element"); # Method from core
但没有任何反应,因为我确信有些东西我没有正确理解。有人可以帮我从这里出去吗?
答案 0 :(得分:0)
您可以创建一个调用原始插件的插件
(function($){
var methods = {
"delete": function() {
console.log("delete");
return this;
}
};
$.fn.deleteable = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return $.fn.list.apply(this,arguments);
} else {
try {
return $.fn.list.apply(this,arguments);
} catch (e) {
$.error('Method ' + method + ' does not exist on jQuery.delete');
}
}
};
})(jQuery);
$(document).list().list("search")
$(document).deleteable().deleteable("delete");
你的代码中有一些拼写错误,我把它们固定在小提琴里。