Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keyup event is not firing - backbone

I've got a problem with the JQuery events in one of my Backbone.Marionette Views. I have defined some click and keyboard events. But some of them are not working. For example I want that the fetch-function is called every time the keyup event is triggered.

So here is the code:

return Backbone.Marionette.ItemView.extend({
  tagName: 'div',
  template: Template,
  events:{
     'click .yes': 'yes',
     'click .no': 'no',
     'keyup #citySearch': 'fetch'
  },
  yes : function() {
    this.close();
  },
  no : function() {
    this.close();
  },
  initialize: function(){
    this.collection = new AreaCollection();
    this.collection.on('sync', this.onShow, this);
    this.sourceArr = [];
  },
  onShow: function() {
      var that = this;
      $('#citySearch').typeahead({
          source: that.sourceArr
      });
  },
  fetch: function(ev) {
    var that = this;
    that.collection.fetch({
      data : {
        query : $(ev.currentTarget).val(),
        type : 'cities'
      },
      success: function(response) {
        for (var i = 0; i < response.length; i++) {
            that.sourceArr.push(response.models[i].get('name'));
        }
      }
    });
  }

});

But the keyup-Event is never fired. I also tried it with the "change"-event, which is also not working. When i use "keydown" or "keypress" instead then everything is fine and the fetch-function is called correctly.

I also tried to bind the event to that input-field manually in the initialize-function with

    $('input#citySearch').bind('keyup',function() {
        console.log('keyup');
    });

But this is also not working. It only works if I bind the event to the input field within my underscore-Template file. But that couldn't be the solution.

Does anybody have an idea what the problem could be?

like image 390
crebuh Avatar asked Jun 10 '13 12:06

crebuh


People also ask

How do I get rid of Keyup event?

onkeyup = null; Inline event handler attributes are assigned to the oneventname property of the element, so just set it to null to detach the event listener.

What is the Keyup event?

The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.


1 Answers

I can think of only one reason for this. And that is:

input#citySearch is not part of your itemView. This means you are NOT binding your fetch function to keyup event inside the container element of your view.

If you want to bind to something outside your view, you can trigger an event to the View in which the element resides.

like image 166
Devesh Kumar Avatar answered Nov 15 '22 11:11

Devesh Kumar