javascript - 使用 Backbone 在预输入建议中包含按钮

标签 javascript jquery backbone.js typeahead.js

我正在寻找一种方法来为预输入建议中的按钮触发不同的方法。

Typeahead suggestions

我在下面使用主干并且我已经创建了要调用的相关事件和方法,但是当我单击时只发生默认的 typeahead:selected 事件,而不是我创建的方法。

编辑

这是这个 View 的相关代码:

var QueryInputView = Backbone.View.extend({
el: $('#query-input'),
initialize: function (options) {
    _.bindAll(this, 'clearInput', 'initWordSuggester', 'initConceptSuggester', 'initTypeAhead');
    this.initTypeAhead();
},
events: {
    'keyup': function (e) {
        if (e.keyCode === 13) {
            var value = this.$el.typeahead('val').trim();
            if (value !== '') {
                kbmed.events.trigger('query-term:add', value);
                this.clearInput();
            }
        }
    },
    'click .add': "addConceptMust",
    'click .add-mustnot': "addConceptMustNot",
    'click .add-should': "addConceptShould"
},
addConceptMust: function (event) {
    // Add concept to filter list
    console.log('adding');
    var id = $(event.currentTarget).attr('id');
    var term = $(event.currentTarget).parent().prev().text();
    app.queryPanel.addQueryConceptMust({'conceptId': id, 'term': term});
},
addConceptMustNot: function (event) {
    // Add concept to filter list
    var id = $(event.currentTarget).attr('id');
    var term = $(event.currentTarget).parent().prev().text();
    app.queryPanel.addQueryConceptMustNot({'conceptId': id, 'term': term});
},
addConceptShould: function (event) {
    // Add concept to filter list
    var id = $(event.currentTarget).attr('id');
    var term = $(event.currentTarget).parent().prev().text();
    app.queryPanel.addQueryConceptShould({'conceptId': id, 'term': term});
},
clearInput: function () {
    this.$el.typeahead('val', '');
},
initWordSuggester: function () {
    var suggestWordsQuery = {
        "text": "%QUERY",
        "phraseSuggestions": {
            "phrase": {
                "field": "article.fulltext",
                "max_errors": 1,
                "gram_size": 3,
                "direct_generator": [
                    {
                        "field": "article.fulltext",
                        "suggest_mode": "popular",
                        "prefix_length": 2,
                        "min_doc_freq": 3
                    }
                ]
            }
        }
    };

    var engineWords = new Bloodhound({
        name: 'words',
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: 'http://' + kbmed.properties.es.hostAndPort + '/' + kbmed.properties.es.docIndex + '/_suggest?source=' + JSON.stringify(suggestWordsQuery),
            filter: function (response) {
                var suggestions = response.phraseSuggestions[0].options;
                if (suggestions && suggestions.length > 0) {
                    return $.map(suggestions, function (suggestion) {
                        return {
                            value: suggestion.text
                        };
                    });
                } else {
                    kbmed.log('Not suggestions');
                    return {}
                }
            }
        }
    });
    engineWords.initialize();
    return engineWords;
},
initConceptSuggester: function () {
    var suggestConceptsQuery = {
        "query": {
            "query_string": {
                "default_field": "term",
                "query": "%QUERY"
            }
        },
        "suggest": {
            "text": "%QUERY",
            "completitionSuggestions": {
                "completion": {
                    "field": "term_suggest"
                }
            }
        }
    };

    var engineConcepts = new Bloodhound({
        name: 'concepts',
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: 'http://' + kbmed.properties.es.hostAndPort + '/' + kbmed.properties.es.sugIndex + '/_search?source=' + JSON.stringify(suggestConceptsQuery),
            filter: function (response) {
                var completitionSuggestions = response.suggest.completitionSuggestions[0].options;
                if (completitionSuggestions && completitionSuggestions.length > 0) {
                    return $.map(completitionSuggestions, function (suggestion) {
                        var concept = JSON.parse(suggestion.text);
                        return {
                            concept: concept,
                            value: concept.term
                        };
                    });
                } else {
                    var hits = response.hits.hits;
                    if (hits && hits.length > 0) {
                        return $.map(hits, function (hit) {
                            var concept = hit._source;
                            return {
                                concept: concept,
                                value: concept.term
                            };
                        });
                    } else {
                        kbmed.log('Not suggestions');
                        return {};
                    }
                }
            }
        }
    });
    engineConcepts.initialize();
    return engineConcepts;
},
initTypeAhead: function () {
    var that = this;
    this.$el.typeahead({
        minLength: 3,
        highlight: true
    },
            {
                source: this.initWordSuggester().ttAdapter()
            },
            {
                source: this.initConceptSuggester().ttAdapter(),
                templates: {
                    header: '<h4 class="concept-name">Concepts</h4>',
                    suggestion: function (data) {
                        var concept = data.concept;
                        return '<div id="'
                                + concept.id
                                + '" class="concept-suggestion" >'
                                + concept.term.substring(0, 45)
                                + '<a style="float: right; margin-left: 3px;" href="#" id="' + concept.id + '" class="btn btn-warning btn-xs add-should"><span class="glyphicon glyphicon-check"></span></a>'
                                + '<a style="float: right; margin-left: 3px;" href="#" id="' + concept.id + '" class="btn btn-danger btn-xs add-mustnot"><span class="glyphicon glyphicon-minus"></span></a>'
                                + '<a style="float: right; margin-left: 3px;" href="#" id="' + concept.id + '" class="btn btn-success btn-xs add"><span class="glyphicon glyphicon-plus"></span></a>'
                                + '<strong style="float: right; font-size: 8pt; color: #837F7F;">'
                                + concept.category.toUpperCase()
                                + '</strong>'
                                + '</div>';
                    }
                }
            }
    ).on('typeahead:selected', function (e, datum) {
        console.log(e);
        console.log(datum);
        e.preventDefault();
        if (datum.concept) {
            kbmed.events.trigger('query-concept:add', datum.concept);
        } else {
            kbmed.events.trigger('query-term:add', datum.value);
        }
        that.clearInput();
    });
}

});

我该怎么做才能让它发挥作用?

最佳答案

如果你想在这个 View 中使用监听器,你需要在这个 View 中渲染带有这些按钮的 html。

现在您正在使用 javascript 编写 html。我永远不会推荐这个。在您的情况下,这意味着 View 不知道这些元素。

所以要解决这个问题:使用模板并在 render() 方法中渲染它。

在上面的示例中,我将为“概念”列表呈现一个额外的 View 。 此 View 可以触发此新 View 。

这是我的意思的一个小例子:

var QueryView = Backbone.View.extend({
    el: $('#query-input'),
    initialize: function (options) {
        _.bindAll(this, 'clearInput', 'initWordSuggester', 'initConceptSuggester', 'initTypeAhead');
    },

    render: function () {

    },

    events: {
        'keyup': 'handleKeyup'
    }

    handleKeyup: function (e) {
       //run new concepts list view
       var conceptsView = new ConceptsListView('queryValue');
    }

});

var ConceptsListView = Backbone.View.extend({ 
     el: '#conceptsList',
     queryResults: {},
     initialize: function (options) {
        //do your query here
        this.queryResults = yourQuery();
        this.render();
     },
     render: function () {
        //Load HTML from template with query results
        //in this template the buttons are to be found
        this.$el.html(template);
     },
     events: {
         'click .add': "addConceptMust",
         'click .add-mustnot': "addConceptMustNot",
         'click .add-should': "addConceptShould"
     },

   addConceptMust: function (e) {

   },
   addConceptMustNot: function (e) {

   },
   addConceptShould: function (e) {

   },

 });

关于javascript - 使用 Backbone 在预输入建议中包含按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39337106/

相关文章:

javascript - 语法错误: The requested module does not provide an export named 'connect'

javascript - 主干网不随 REST 请求发送属性

javascript - 触发 jQuery ("#collapseMenu").hide();按 Esc 键时

javascript - 生成 SVG 形状

javascript - 针对 IE8 的 PNG 淡入淡出修复

jquery序列化多选

javascript - jQuery 获取先前的输入值

javascript - 突出显示 html 字符串中的关键字

javascript - Backbone.js 再次渲染 View 还是重新创建?

javascript - 告诉屏幕阅读器页面已在 Backbone/Angular 单页应用程序中更改