Backbone event firing on click OR press enter

Melbourne2991 picture Melbourne2991 · Dec 4, 2013 · Viewed 13.4k times · Source

I am new to backbone and I am looking for a way for my button to be triggered when I press Enter as well as clicking. Currently showPrompt only executes on a click. What is the cleanest DRYest way to have it execute on pressing Enter as well, preferably only for that input field.

(function () {

  var Friend = Backbone.Model.extend({
    name: null
  });

  var Friends = Backbone.Collection.extend({
    initialize: function (models, options) {
      this.bind("add", options.view.addFriendLi);
    }
  });

  var AppView = Backbone.View.extend({
    el: $("body"),
    initialize: function() {
      this.friends = new Friends(null, {view: this});
    },
    events: {
      "click #add-friend":  "showPrompt",
    },
    showPrompt: function () {
      var friend_name = $("#friend-name").val()
      var friend_model = new Friend({ name:friend_name });
      this.friends.add( friend_model );
    },
    addFriendLi: function (model) {
      $("#friends-list").append("<li>" + model.get('name') + "</li>");
    }
  });

  var appView = new AppView; 

}());

Also where can I read more about this kind of event binding? Do backbone events differ from JS or jQuery events in how they're defined?

Answer

Niranjan Borawake picture Niranjan Borawake · Dec 4, 2013

You can add one more event to your events hash in AppView.

events: {
   "click #add-friend":  "showPrompt",
   "keyup #input-field-id" : "keyPressEventHandler"
}

Where #input-field-id is the one you want to add event on.

Then add eventHandler in AppView.

keyPressEventHandler : function(event){
    if(event.keyCode == 13){
        this.$("#add-friend").click();
    }
}

NOTE : This code is not tested but you can think doing it in this way.

Have a look at this to understand how Backbone handles events in a View.