what is the event name for typing on a textfield on a view in backbone.js?

32 Views Asked by At

Ive created a view that displays information about quizzes I got from MySQL database. In order to search for a specific quiz I have implemented a search bar in a new view called MyQuizSearchView. Below is my code for MyQuizSearchView,

var MyQuizSearchView = Backbone.View.extend({
            model: myQuizC,
            el: $('#search'),
            events: {
                "change input": "searchEvent"
            },
            initialize: function() {
                this.render()
            },
            render: function() {
                var self = this;

                // var block1 = '  <input type="text" placeholder="What are you looking for?" onkeyup="searchByTags(\'' + this.value + '\')">'
                var block1 = '  <input type="text" placeholder="What are you looking for?">'
                self.$el.append(block1)

            },
            searchEvent: function(event) {
                console.log("heyyy")
            }
        })
        var myQuizSearchView = new MyQuizSearchView();

I want to trigger a function named searchEvent when the user starts typing on the text field.How can I implement the below onkeyup method using backbone view events?

<input type="text" placeholder="What are you looking for?" onkeyup="searchByTags(this.value)">
1

There are 1 best solutions below

0
Julian On

Simply use keyup instead of change inside your events map.

var MyQuizSearchView = Backbone.View.extend({
    model: myQuizC,
    el: $('#search'),
    events: {
        "keyup input": "searchEvent"
    },
    // ...
});

If the search is expensive, you may want to throttle the searchEvent method so it does not run more often than necessary.

var MyQuizSearchView = Backbone.View.extend({
    model: myQuizC,
    el: $('#search'),
    events: {
        "keyup input": "searchEvent"
    },
    initialize: function() {
        this.render();
        this.searchEvent = _.throttle(this.searchEvent, 500);
    },
    // ...
});