Javascript 自定义JQuery插件方法错误

Javascript 自定义JQuery插件方法错误,javascript,jquery,jquery-plugins,Javascript,Jquery,Jquery Plugins,我一直在为我的一个web应用程序编写一个自定义jquery插件,但我遇到了一个奇怪的错误,我认为这是因为我不熟悉面向对象编程 当我试着运行$(“.list组”).updateList('template','some template')两次时,我遇到了一个bug,第一次运行得很好,但第二次运行相同的命令时,我得到的对象不是函数错误。以下是插件代码: (function($){ defaultOptions = { defaultId: 'selective_update

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

当我试着运行$(“.list组”).updateList('template','some template')两次时,我遇到了一个bug,第一次运行得很好,但第二次运行相同的命令时,我得到的对象不是函数错误。以下是插件代码:

(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));
当我访问此.template时,我注意到了一件事—它位于一个数组中,因此我必须调用此.template[0]来获取字符串…我不知道它为什么这样做,但我怀疑这与我得到的错误有关。也许它可以在第一次分配字符串,但不能在下一次分配?任何帮助都将不胜感激

谢谢:)

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

this.template = ["some template"];
因此,下次运行
instance[opt](args)
时,它将尝试执行该数组,就像它是一个函数一样,并因此获得not a function错误


错误与哪一行代码相关?当我使用“模板”输入调用我的插件两次(调用该函数)时,我得到了错误,我想我已经将它隔离到了这一行。模板=模板;该行不会导致
对象不是函数错误
错误消息通常在浏览器控制台中有与其关联的代码行。我认为,最有可能导致错误的原因是
instance[opt](args)
-在该行前面放一个
console.log(“opt is”+opt)
。添加
console.dir(instance)可能也不错也在那里。谢谢,就是这里!绝对没有意识到我的名字不是最聪明的哈哈
this.template = ["some template"];