我正在编写一个插件,它会在需要时显示一个小助手。它应该像这样启动:
$(el).santasLittleHelper([options])
然后插件有一些“事件”,就像 jquery UI 一样,它们应该像这样被触发:
$(el).santasLittleHelper('evetnName', [options])
我有一个原型(prototype)可以工作,但我担心我的结构 future 会出现问题。当我继续处理它时,内存溢出或遇到变量和函数范围的其他问题。这是一个大纲:
(function($) {
$.fn.santasLittleHelper = function(p1, p2) {
return this.each(function() {
var o = {
showSpeed: 50,
hideSpeed: 50,
duration: 5000,
delay: 0
}
var el = $(this);
function init() {
console.log('init 1');
}
var events = {
show: function(opt) {},
hide: function(opt) {},
pulse: function(opt) {}
}
if(p1 == undefined) {//This is obviously the init call
init();
}
if(typeof(p1) == 'object') {
//Correctly added parameters would then mean that p1 is options
//and is the only parameter added so we store the options and init
$.extend(o, p1);
init();
}
if(typeof(p1) == 'string') {
//This is a call to an "event".
//call the "event" function and supply possible options as arg
events[p1](p2);
}
});
}
})(jQuery);
可以为每个事件调用提供选项,但在这种情况下应该只在该事件函数范围内可用。这是因为我可能希望帮助者通过在 init 调用中提供选项来跳出我创建他时所处的心理状态。
由于代码开头声明的变量,这种方法是否会在每次调用 $(el).santasLittleHelper('event') 时填满内存?
我认为它看起来很干净并且可以理解,但是可以做改进吗?
最佳答案
根据描述的做法here ,在我看来你做对了,但如果可能的话,我会尝试使 o 和事件独立于每个(之前声明它并作为可选参数传递,如果需要覆盖,否则使用在每个外部声明的唯一?)
关于javascript - 制作 JQuery 扩展 $.fn.extension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7545604/