backbone.js: set focus to input after render

ragulka picture ragulka · Jan 9, 2012 · Viewed 8.1k times · Source

I have a Model that has 1 input. Also, I have a Collection. Now, when I add a model to the collection, I want to set the focus to it's input. To be precise, I need to set the focus on the newly created model view's input.

However, I can't seem to get it to work. Here's my function that adds the model's view to the collection view:

addOne: function(InvoiceItem) {
    var view = new InvoiceItemView({model: InvoiceItem});
    this.$('tr[data-id="'+InvoiceItem.get('after')+'"]').after(view.render().el);
    this.$('tr[data-id="'+InvoiceItem.cid+'"]').css('background', 'green');
    this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
},

The problem is, the third call: this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus(); does not do anything. And it's weird, because it seems that I can only do DOM manipulation on the root element tr, and on nothing else besides that.

It seems to me that jQuery doesn't know that the element exists, which is weird, because when I do alert(this.$('tr[data-id="'+InvoiceItem.cid+'"] input').length) I get 1, which indicates that the element exists.

What it is that I am doing wrong here?

Answer

jeroen.verhoest picture jeroen.verhoest · Apr 26, 2012

Using _.defer fixed my problem:

var $this = this;
_.defer(function(){
  $this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
});