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:
- I see the alert, but
updateSpanis not being fired. I think I’m usingthisincorrectly in the callback, but how should I do it? - Is
initializenow the right place to set the typeWatch event listener, or can I continue to use theeventsfield as I did before?
You aren’t actually calling
updateSpan, and you’re right thatthiswont be the correct thing. Easiest way to solve it is to just capture the view into another variable first:As for your second question, usually I will attach functionality like this in
initializeif it’s on the base element and inrenderif it’s not, so I think in this case you’ve probably got it right.