我已经找到了不错的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
可以用这个模板调用函数吗?
你可以在小提琴上玩
发布于 2016-04-15 15:00:20
我相信第1031项是罪魁祸首
setTimeout(function() {
newSol.init();
}, 0);
由于init是延迟的,所以当您立即调用它时,代码还没有准备好。最重要的解决办法是推迟调用,但是没有人保证它将被初始化。
setTimeout(function(){s.selectAll()},1000);
更好的解决方案是在初始化后使用插件的事件连接到其中。
$('#my-select').searchableOptionList({
maxHeight: '150px',
events: {
onInitialized: function() {
this.selectAll();
}
}
});
https://stackoverflow.com/questions/36649753
复制相似问题