gpt4 book ai didi

javascript - 自定义 JQuery 插件方法错误

转载 作者:行者123 更新时间:2023-12-03 12:04:53 25 4
gpt4 key购买 nike

我一直在为我的一个 Web 应用程序编写一个自定义 jquery 插件,但遇到了一个奇怪的错误,我认为这是由于我不熟悉面向对象编程。

当我尝试运行 $(".list-group").updateList('template', 'some template') 两次时,我遇到了这个错误,第一次它工作得很好,但第二次运行相同的命令时,我得到一个对象不是函数错误。这是插件代码:

(function($){
defaultOptions = {
defaultId: 'selective_update_',
listSelector: 'li'
};

function UpdateList(item, options) {
this.options = $.extend(defaultOptions, options);
this.item = $(item);
this.init();
console.log(this.options);
}
UpdateList.prototype = {
init: function() {
console.log('initiation');
},
template: function(template) {
// this line is where the errors come
this.template = template;
},
update: function(newArray) {
//update code is here
// I can run this multiple times in a row without it breaking
}
}

// jQuery plugin interface
$.fn.updateList = function(opt) {
// slice arguments to leave only arguments after function name
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var item = $(this), instance = item.data('UpdateList');
if(!instance) {
// create plugin instance and save it in data
item.data('UpdateList', new UpdateList(this, opt));
} else {
// if instance already created call method
if(typeof opt === 'string') {
instance[opt](args);
}
}
});
}
}(jQuery));

当我访问 this.template 时,我注意到一件事 - 它在一个数组中,所以我必须调用 this.template[0] 来获取字符串...我不知道为什么要这样做,但我怀疑这与我遇到的错误有关。也许第一次可以分配字符串,但下一次就不行了?任何帮助,将不胜感激!

谢谢:)

最佳答案

this.template = template

实际上是您的问题,因为您正在覆盖实例上设置的函数。当您将其作为参数传递给初始 template 函数时,您最终会将其覆盖到您的 args 数组中。它基本上会这样做:

this.template = ["some template"];

因此,下次 instance[opt](args) 运行时,它将尝试执行该数组,就好像它是一个函数一样,因此会出现“不是函数”错误。

JSFiddle

关于javascript - 自定义 JQuery 插件方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25231156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com