从 jquery 插件样板代码调用函数

Invoke function from jquery plugin boiler plate code

我找到了不错的 jQuery 插件,它使用样板模板。一切正常,但我无法调用内部函数来获取选定的项目。 该插件的构建如下:

    (function ($, window, document) {
    'use strict';

    // constructor
    var SearchableOptionList = function ($element, options) {
        this.$originalElement = $element;
        this.options = options;

        this.metadata = this.$originalElement.data('sol-options');
    };

    // plugin prototype
    SearchableOptionList.prototype = {

        DATA_KEY: 'sol-element',

        // default option values
        defaults: {            
            ... 
        },

        // initialize the plugin
        init: function () {
            this.config = $.extend(true, {}, this.defaults, this.options, this.metadata);

            ...

            return this;
        },

        //some functions
        ...

        selectAll: function () {
            ...
        },

        deselectAll: function () {
            ...
        },

        getSelection: function () {
            return this.$selection.find('input:checked');
        }
    };

    // jquery plugin boiler plate code
    SearchableOptionList.defaults = SearchableOptionList.prototype.defaults;
    window.SearchableOptionList = SearchableOptionList;

    $.fn.searchableOptionList = function (options) {
        var result = [];
        this.each(function () {
            var $this = $(this),
                $alreadyInitializedSol = $this.data(SearchableOptionList.prototype.DATA_KEY);

            if ($alreadyInitializedSol) {
                result.push($alreadyInitializedSol);
            } else {
                var newSol = new SearchableOptionList($this, options);
                result.push(newSol);

                setTimeout(function() {
                    newSol.init();
                }, 0);
            }
        });

        if (result.length === 1) {
            return result[0];
        }

        return result;
    };

}(jQuery, window, document));

您可以在 GitHub.

上找到完整代码

我尝试调用 getSelection 函数,如下所示:

// initialize sol
    var s = $('#my-select').searchableOptionList({
        maxHeight: '150px',
        showSelectAll: true
    });

    s.selectAll();

我收到一个错误:

TypeError: this.config is undefined

是否可以使用此样板模板调用函数?

你可以在jsfiddle

上玩

我相信 line 1031 是罪魁祸首

        setTimeout(function() {
            newSol.init();
        }, 0);

由于 init 被延迟,当您立即调用它时,代码还没有准备好。最简单的解决方法是也推迟你的调用,但不能保证它会被初始化。

setTimeout(function(){s.selectAll()},1000);

更好的解决方案是使用插件的events在初始化时挂钩。

$('#my-select').searchableOptionList({
  maxHeight: '150px',
  events: {
    onInitialized: function() {
      this.selectAll();
    }
  }
});

fiddle