如何通过传递参数和覆盖我自己的回调来自定义jquery小部件?

bra*_*ter 4 jquery jquery-ui callback jquery-callback jquery-widgets

我是jquery的新手,最近根据我的需要量身定制了jquery组合框.但是,我需要在我的网站上的其他位置重用此组件.我基本上需要传入一些参数和一个回调函数,应该调用它来处理jquery中的某些事件.我正在努力学习语法并尝试找到jquery-way of things:

为了给你一个样本,这里是sourcecombobox -> input -> autocomplete -> 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));
}
Run Code Online (Sandbox Code Playgroud)

这里updateOptions(...),filterOptionsForResponse(select, term)是简单的JavaScript功能.

为了重用,我需要指定一个回调来处理source我创建的每个组合框的实例.

有人能指出我如何做到这一点的正确方向?

mu *_*ort 6

唯一有用的小部件工厂文档在wiki中,并:

属性:
[...]
this.options
当前用于插件配置的选项.在实例化时,用户提供的任何选项都将自动与任何默认值合并

所以如果你需要提供一个回调函数source,那么你会这样说:

$("#searchbox").combobox({
    source: function(request, response) { /* ... */ }
});
Run Code Online (Sandbox Code Playgroud)

然后在你的插件里面看看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,
            //...
Run Code Online (Sandbox Code Playgroud)

您不必包含默认选项,但这样做几乎总是有意义的(即使您只是将其用于文档目的).