【发布时间】:2016-04-15 14:22:10
【问题描述】:
我找到了不错的 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上玩耍
【问题讨论】:
标签: javascript jquery jquery-plugins boilerplate