在 typeahead 上选择的事件函数调用了很多次,而它应该只调用一次

On typeahead selected event function is calling many times when it should one only

我有以下使用 typeahead.js 的功能,它绑定在输入字段上。

问题是当用户将从下拉列表中 select 值时,我试图传递自定义函数。

所以第一次它只发送正确的值(一次)。对于下一个 selection,它发送相同的值两次。当 select 从下拉列表中添加新内容时,它会随机发送 4 次。 selection from dropdown 它应该只传递一次变量。

$(document).on('mouseenter', '.js-ma-product-autocomplete', function (e) {

        var current_handler = $(this).attr('id');
        $('#' + current_handler).typeahead("destroy");
        var current_selected_id = $(this).siblings('.js-ma-linked-product-id').attr('id');
        var current_selected_type = $(this).siblings('.js-ma-linked-product-type').val();
        var current_selected_container = $(this).siblings('.js-ma-linked-product-container').val();
        var current_selected_btn = $(this).siblings('.js-ma-linked-product-add-btn').val();
        var initialize_master_agent_products_typeahead;

        initialize_master_agent_products_typeahead = function () {
            var master_agent_products_typeahead;
            master_agent_products_typeahead = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace("name"),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                remote: {
                    url: "/productions/mas_products_autocomplete?query=%QUERY",
                    replace: function (url, uriEncodedQuery) {
                        return url.replace("%QUERY", uriEncodedQuery) + '&product_type=' + encodeURIComponent(current_selected_type)
                    },
                    filter: function (list) {
                        if (list.length == 0) {
                            $('#' + current_selected_id).val('');
                        }
                        return list;
                    }
                }
            });
            master_agent_products_typeahead.initialize();
            $('#' + current_handler).typeahead(null, {
                displayKey: "name",
                source: master_agent_products_typeahead.ttAdapter(),
                templates: {empty: "<div> No matching products found </div>"}
            });
            $('#' + current_handler).one('typeahead:selected', function (event, datum, name) {
                var count = 1;
                $('#' + current_selected_id).val(datum.id);
                show_options(current_selected_type);
                create_fields(current_selected_id, current_selected_type, current_selected_container, current_selected_btn, datum.id, datum.name, count++); // from this part its calling more than once.
            });
        };
        initialize_master_agent_products_typeahead();
    });

function create_fields(c_p_id, c_p_type, c_p_container, c_p_btn, l_p_id, l_p_name, count){
    // var minNumber = 300;
    // var maxNumber = 400;
    // var randomNumber = randomNumberFromRange(minNumber, maxNumber);

    // debugger;

    console.log(c_p_id);
    console.log(c_p_type);
    console.log(c_p_container);
    console.log(c_p_btn);
    console.log(l_p_id);
    console.log(l_p_name);
    console.log(count);
    console.log('*****************');

    //here it sends values multiple times

}

看下面我只打了一次就显示为:

在反复使用不同的选项之后,我发现我在每次鼠标输入时再次初始化预输入。

因此,解决方法是每个字段只调用一次,而不是一直调用它。并在其上使用 one 会使它发挥作用。

这是最终的工作代码:

$('.js-ma-product-autocomplete').one('mouseenter', function (e) {

        var current_handler = $(this).attr('id');

        console.log(current_handler);

        $('#' + current_handler).typeahead("destroy");
        var c_p_id = $(this).siblings('.js-ma-product-id').val();
        // var c_lp_id = $(this).siblings('.js-ma-linked-product-id').attr('id');
        var c_p_type = $(this).siblings('.js-ma-linked-product-type').val();
        var c_container = $(this).siblings('.js-ma-linked-product-container').val();
        var c_btn = $(this).siblings('.js-ma-linked-product-add-btn').val();
        var initialize_master_agent_products_typeahead;

        initialize_master_agent_products_typeahead = function () {
            var master_agent_products_typeahead;
            master_agent_products_typeahead = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace("name"),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                remote: {
                    url: "/productions/mas_products_autocomplete?query=%QUERY",
                    replace: function (url, uriEncodedQuery) {
                        return url.replace("%QUERY", uriEncodedQuery) + '&product_type=' + encodeURIComponent(c_p_type)
                    },
                    filter: function (list) {
                        if (list.length == 0) {
                            //$('#' + c_lp_id).val('');
                        }
                        return list;
                    }
                }
            });
            master_agent_products_typeahead.initialize();
            $('#' + current_handler).typeahead(null, {
                displayKey: "name",
                source: master_agent_products_typeahead.ttAdapter(),
                templates: {empty: "<div> No matching products found </div>"}
            });
            $('#' + current_handler).on('typeahead:selected', function (event, datum, name) {
                // $('#' + c_lp_id).val(datum.id);
                show_options(c_p_type);
                create_fields(c_p_id, c_p_type, c_container, c_btn, datum.id, datum.name);
            });
        };
        initialize_master_agent_products_typeahead();
    });

    function show_options(type) {
        if (type == 'compatible') {
            $('#subsidize_rent_lease_options').removeClass('hide');
        }
    }

    function create_fields(c_p_id, c_p_type, c_p_container, c_btn, c_lp_id, c_lp_name){

        var randomNumber = randomNumberFromRange(300, 400);

        console.log(c_p_id);
        console.log(c_p_type);
        console.log(c_p_container);
        console.log(c_btn);
        console.log(c_lp_id);
        console.log(c_lp_name);

        $("#" + c_btn).removeAttr('disabled', false);

        var item_container = $('<div/>', {'class': "div_" + randomNumber});

        $('<input>').attr({
            type: 'hidden',
            name: "product[linked_products_attributes]["+randomNumber+"][product_id]",
            value: c_p_id
        }).appendTo(item_container);

        $('<input>').attr({
            type: 'hidden',
            name: "product[linked_products_attributes]["+randomNumber+"][linked_product_id]",
            value: c_lp_id
        }).appendTo(item_container);

        $('<input>').attr({
            type: 'hidden',
            name: "product[linked_products_attributes]["+randomNumber+"][link_type]",
            value: c_p_type
        }).appendTo(item_container);

        $('<input>').attr({
            type: 'hidden',
            name: "product[linked_products_attributes]["+randomNumber+"][name]",
            value: c_lp_name
        }).appendTo(item_container);

        $("#" + c_p_container).append(item_container);

    }

    function randomNumberFromRange(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }