The view part of my code using Backbone.js is something like this:
var myView = Backbone.View.extend({
events: {
'focus .cell input' : "updateCurrentCell"
},
updateCurrentCell: function(event) {
console.log('updateCurrentCell called');
// Update the current cell.
}
}
Whenever the input element gets focus, the function is called twice. I tried printing the stack trace using console.trace()
. It shows that once the function call originated from focus event while the next time from focusin.
My attempts to find out how to prevent one of these events getting fired lead me nowhere. How can I fix this?
Backbone.View uses delegateEvents to bind the events listed in your events object. If you take a look at the source, you'll see that delegateEvents
uses jQuery.delegate to do so.
There's a note in the jquery docs for .focus() that's probably relevant:
The focus event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the focus event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping focus to the focusin event in its event delegation methods, .live() and .delegate().
In theory, this should just work fine, but since you're getting both, perhaps you could try to just listen for the .focusin() event, as it supports the kind of event bubbling .delegate() listens for and is what jQuery is trying to map 'focus' to anyway.