jQuery UI自动完成不使用原始项目

时间:2018-12-05 02:11:59

标签: javascript jquery jquery-ui jquery-ui-autocomplete

我有以下内容:

class Department {
    constructor(data) {
        this.id = data && data.id || null
        this._name = data && data.name || null
    }

    get name() {
        return this._name
    }
    set name(v) {
        this._name = (v || "").trim() || null
    }
}

// In a different module:
import Department from "./Department"

async function searchDepartments(request, response) {
    let departments = []
    let result = await getDepartmentsFromServer(request.term)
    result.data.map((d) => {
        departments.push(new Department(d))
    })
    response(departments)
}

$("#myAutocomplete").autocomplete({
    minLength: 1,
    delay: 500,
    source: searchDepartments,
    select: function (e, ui) {
        e.preventDefault()
        $(this).val(ui.item.name) // ui.item.name is undefined; why?
    },
})
.each(function () {
    $(this).autocomplete("instance")._renderItem = function (ul, item) {
        let itemTemplate = "<div>" + item.name + "</div>"  // item.name is undefined; why?
        return $("<li>")
            .append(itemTemplate)
            .appendTo(ul)
    }
})

问题在于,自动完成功能在内部使用了不同的项目对象;不是原始的随响应(部门)提供的。我在jquery自动完成源中找到以下代码:

// At line 2527
__response: function( content ) {
    if ( content ) {
        content = this._normalize( content );
    }
    ...
},

...

// At line 2566
_normalize: function( items ) {

    // assume all items have the right format when the first item is complete
    if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
        return items;
    }
    return $.map( items, function( item ) {
        if ( typeof item === "string" ) {
            return {
                label: item,
                value: item
            };
        }
        return $.extend( {}, item, {
            label: item.label || item.value,
            value: item.value || item.label
        } );
    } );
},

使用$ .extend看起来,我部门对象的getter / setter丢失了。有解决问题的建议吗?

PS:当然,在这种情况下,我可以使用item._name,但是我需要更通用的方法。

1 个答案:

答案 0 :(得分:0)

我建议先尝试制作Department对象,然后使用getter函数,然后再将结果发送回response()

async function searchDepartments(request, response) {
    let departments = []
    let result = await getDepartmentsFromServer(request.term)
    $.each(result, function(k, d){
      var item = new Department(d);
      departments.push(item.name);
    });
    response(departments)
}

这会随后将字符串数据数组发送到response(),它将得到更好的处理。

希望有帮助。