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

标签 jquery jquery-ui callback jquery-callback jquery-widgets

我对 jquery 非常陌生,最近定制了 jquery combobox根据我的需要。但是,我需要在网站的其他地方重用此组件。我本质上需要传递一些参数和一个回调函数,应该调用它们来处理 jquery 中的某些事件。我正在努力解决语法问题,并试图找到 jquery 的做事方式:

为了给您一个示例,这里是 combobox -> input -> autocomplete -> sourcesource:

(创建了一个工作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/

相关文章:

javascript - 为什么无法应用转换 :none to my elements?

javascript - 如何禁用 HTML 页面中的元素但能够使用 jQuery Draggable 拖动它?

jquery-ui-multiselect-widget 加载数据时闪烁?

ios - performSegueWithIdentifier 在回调函数中不起作用?

jQuery 通过自定义属性获取元素

javascript - Highchart.js 在纯 IE8 中无法正常工作

javascript - 我如何在 Angular js 中将 64 位 HTML 文件显示到 iframe 中

jquery-ui - jquery datepicker 不显示在动态添加的输入上

jquery - 带有放大弹出回调的无限滚动

javascript - 如何在触发 'end' 事件之前使用 fast-csv 处理 Node js 中 csv 文件的最后一行?