Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js: set focus to input after render

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?

like image 237
ragulka Avatar asked Jan 09 '12 14:01

ragulka


2 Answers

Using _.defer fixed my problem:

var $this = this;
_.defer(function(){
  $this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
});
like image 80
jeroen.verhoest Avatar answered Sep 22 '22 00:09

jeroen.verhoest


Instead of this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();

try this

$(view.render().el).find('input').focus();
like image 25
Paul Avatar answered Sep 19 '22 00:09

Paul