O
O
olafars2015-08-04 22:54:56
backbone.js
olafars, 2015-08-04 22:54:56

How does an event work in Backbone?

Greetings! I started to deal with Backbone.js and a question arose when working with keyboard events, this is the first experience with Backbone.js, so I need help.

SearchView = Backbone.View.extend({
  el: $('.platform'),

  events: {
    'keydown': 'edit'
  },

  initialize: function () {
    console.log('initialized!');
  },

  edit: function(event) {
    console.log('Work!');
  },

});

var searchView = new SearchView();

It is necessary that when certain keys are pressed, some code will work, for example:
edit: function(event) {
    if (event.keyCode == 37) {

    } else if(event.keyCode == 39) {

                }
  },

How can I make the edit function always work in Backbone when a key is pressed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2015-08-05
@k12th

Well, if on the forehead, then you can like this:

var SearchView = Backbone.View.extend({
    events: {
        'keydown': 'checkKeyCode'
    },

    initialize: function () {
        // ...
        
        this.on('keyCode27', this.onEscape);
        this.on('keyCode13', this.onEnter);
        this.on('keyCode8', this.onTab);
    },

    checkKeyCode: function (event) {
        this.trigger('keyCode' + event.keyCode, event); // pass event along so we can do event.preventDefault
    }
});

As an option, do not throw events, but immediately call the necessary methods, such asthis['keyCodeHandler'](event.keyCode)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question