在预先输入的情况下,所选事件函数仅应调用一次才调用多次

时间:2019-01-28 15:43:03

标签: javascript jquery ruby-on-rails typeahead.js twitter-typeahead

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

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

因此,它第一次仅发送正确的值(一次)。对于下一个选择,它将两次发送相同的值。从下拉列表中选择“新”时,它将随机发送4次。 从下拉列表中选择时,它应该只传递一次变量。

$(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

}

见下文,我只键入了一次,它显示为: enter image description here enter image description here enter image description here

1 个答案:

答案 0 :(得分:0)

反复使用不同的选项后,我想到要在每个mouseent上再次初始化输入。

因此,一种解决方法是每个字段仅一次调用一次,而不是始终调用一次。并在其上使用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);
    }