我对 jquery 非常陌生,最近定制了 jquery combobox根据我的需要。但是,我需要在网站的其他地方重用此组件。我本质上需要传递一些参数和一个回调函数,应该调用它们来处理 jquery 中的某些事件。我正在努力解决语法问题,并试图找到 jquery 的做事方式:
为了给您一个示例,这里是 combobox -> input -> autocomplete -> source
的 source
:
(创建了一个工作jsfiddle以供引用)
source: function( request, response ) {
// implements retrieving and filtering data from the select
var term = request.term;
var prefixLength = 2;
if (term.length >= prefixLength) {
var abbreviation = term.substring(0, prefixLength);
if(!(abbreviation.toLowerCase() in cache)){
cache[abbreviation.toLowerCase()] = 1;
$.ajax({
url: "/wah/destinationsJson.action",
dataType: "json",
data: {
term: abbreviation
},
type: "GET",
success: function(data) {
if(!data || !data.cities || !data.cities.length){
// response(["No matches for " + term]);
return;
}
updateOptions(select, data.cities);
response(filterOptionsForResponse(select, term));
return;
}
});
}
}
response(filterOptionsForResponse(select, term));
}
这里 updateOptions(...)
、filterOptionsForResponse(select, term)
是简单的 JavaScript 函数。
为了重用,我需要指定一个回调来处理我创建的每个组合框实例的source
。
有人可以为我指明如何执行此操作的正确方向吗?
最佳答案
唯一有用的小部件工厂文档位于 wiki 和 that says 中。 :
Properties:
[...]
this.options
The options currently being used for the plugin configuration. On instantiation, any options provided by the user will automatically be merged with any default values
因此,如果您需要为 source
提供回调函数,那么您会这样说:
$("#searchbox").combobox({
source: function(request, response) { /* ... */ }
});
然后在你的插件中,查看this.options.source
:
$.widget("ui.combobox", {
options: {
// Default options go here...
},
_create: function() {
//...
input = $("<input>").appendTo(wrapper).val(value).addClass("ui-state-default").autocomplete({
source: this.options.source,
//...
您不必包含默认选项,但这样做几乎总是有意义的(即使您只是将其用于文档目的)。
关于jquery - 如何通过传递参数并覆盖我自己的回调来自定义 jquery 小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10845390/