Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top