Reputation: 2527
I have a view with a login form and I'm attempting to set the focus after the view is rendered. I tried this, but it didn't work:
class App.Views.Login extends Backbone.View
template: template("login")
events:
"click button": "login"
render: ->
@$el.html @template(@)
@$el.find("#email").focus()
Also tried this;
class App.Views.Login extends Backbone.View
template: template("login")
events:
"click button": "login"
render: ->
@$el.html(@template(@)).ready =>
@$el.find("#email").focus()
Added router to show how Login is attached to the DOM:
class App.Routers.App extends Backbone.Router
initialize: ->
chrome = new Spokely.Views.Chrome el: $("#app")
chrome.render()
@mainEl = $("#main")
routes:
"": "index"
"ad/:id": "show"
"about": "about"
"login": "login"
"signup": "signup"
login: ->
view = new Spokely.Views.Login()
@mainEl.html view.render().el
What am i missing?
Upvotes: 0
Views: 3703
Reputation: 1963
Post is very old, but still I would like to answer here as it might help someone. There is slightly better and easier approach. We can use onDomRefresh event to set the focus. onDomRefresh event will be called anytime the view has been rendered, shown, and then re-rendered. we can use it as following:
onDomRefresh:function(){
@$el.find("#email").focus()
}
Hope this helps someone.
Upvotes: 0
Reputation: 7708
It seems that although you set the focus within the view, when you attach the login view to the main DOM, the focus is reset (it is not focused any more). Try:
login: ->
view = new Spokely.Views.Login()
@mainEl.html view.render().el
$("#email").focus()
Use Jquery to call the focus method after you have attached the Login
view to the main DOM. This will work for sure.
Alternatively, you can pass the '#main' as el to the Login view itself. Like:
login: ->
view = new Spokely.Views.Login el: $("#main")
view.render()
Then you dont need to add code to the router, your initial code should work.
Upvotes: 2