Richard
Richard

Reputation: 32909

Backbone.js: calling custom events inside a View?

I would like to update part of my view when the user types into a input field. Initially I bound to the keyup event listener within the View's events field, and that worked well:

window.AppView = Backbone.View.extend({
 el: $("#myapp"),
 events: {
   "keyup #myInput": "updateSpan",
 }, ...
 updateSpan: function() { 
     this.span.text(this.input.val());
 }, ...
});

But then I realised that keyup updated too often and made the app slow. So I decided to use the typeWatch plugin so the event would only fire the user stopped typing. But now I don't know how to set the custom event listener in Backbone. Currently I have this:

window.AppView = Backbone.View.extend({
 initialize: { 
  var options = {
      callback: function(){ 
        alert('event fired'); 
        this.updateSpan; 
      },
      wait:750
  }
  this.input.typeWatch(options);
 }, ...
 updateSpan: function() { 
     this.span.text(this.input.val());
 }, ...
});

Two questions:

  1. I see the alert, but updateSpan is not being fired. I think I'm using this incorrectly in the callback, but how should I do it?
  2. Is initialize now the right place to set the typeWatch event listener, or can I continue to use the events field as I did before?

Upvotes: 0

Views: 749

Answers (1)

rfunduk
rfunduk

Reputation: 30442

You aren't actually calling updateSpan, and you're right that this wont be the correct thing. Easiest way to solve it is to just capture the view into another variable first:

  var v = this;
  var options = {
    callback: function() {
      alert('event fired');
      v.updateSpan();
    },
    wait: 750
  };
  this.input.typeWatch(options);

As for your second question, usually I will attach functionality like this in initialize if it's on the base element and in render if it's not, so I think in this case you've probably got it right.

Upvotes: 1

Related Questions