自定义JQuery插件方法错误

Custom JQuery Plugin Method error

本文关键字:错误 方法 插件 JQuery 自定义      更新时间:2023-09-26

我一直在为我的一个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));

我注意到一件事,当我去访问这个。template -它在一个数组中,所以我必须调用这个。模板[0]获取字符串…我不知道它为什么这样做,但我怀疑它与我得到的错误有关。也许第一次可以赋值字符串,但第二次不行?任何帮助将不胜感激!

谢谢

this.template = template

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

this.template = ["some template"];

因此,instance[opt](args)下次运行时,它将尝试执行该数组,就好像它是一个函数,因此得到非函数错误。

JSFiddle