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

时间:2016-04-15 14:22:11

标签: javascript jquery jquery-plugins boilerplate

我找到了很好的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

上玩游戏

1 个答案:

答案 0 :(得分:1)

I believe line 1031 is the culprit

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

Since the init is deferred the code is not ready when you call it right away. The esiest fix is to defer your call too, but there is no gurantee that it will be initialized.

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

The better solution is to use the plugin's events to hook into when it has been initialized.

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

fiddle