【问题标题】:On typeahead selected event function is calling many times when it should one only在 typeahead selected 事件函数被调用多次时,它应该只调用一次
【发布时间】:2019-01-28 15:43:02
【问题描述】:

我有以下使用 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

}

见下文,我只输入了一次,它显示为:

【问题讨论】:

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


    【解决方案1】:

    在使用不同的选项来回切换之后,我发现我在每个 mouseenter 上再次初始化 typeahead。

    因此,解决方法是每个字段只调用一次,而不是一直调用它。并且在它上面使用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);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 2019-04-18
      • 1970-01-01
      相关资源
      最近更新 更多