私は次のバックボーンビューを持っています:
core.views.Login = Backbone.View.extend(
{
el: '#main-content-wrapper',
events:
{
'focus #username': 'usernameFocus',
'blur #username': 'usernameBlur'
},
initialize: function()
{
this.render();
},
render: function()
{
var html = unlocked.renderTemplate('login', 'core');
this.$el.empty().html(html);
$('#username').focus();
return this;
},
usernameFocus: function(event)
{
console.log('focus');
if($(event.target).val() == 'Username')
{
$(event.target).val('');
}
},
usernameBlur: function(event)
{
if($(event.target).val() == '')
{
$(event.target).val('Username');
}
}
});
私が抱えている問題は、次のことを行う場合です:$('#username')。focus(); :レンダリングでは、:usernameFocus:イベントがまだアタッチされていません。私が考えることができる解決策は2つだけです。
- setTimeoutを使用する-このオプションは技術的には機能しますが、実際のオプションとは見なしません
- レンダリングでイベントを手動で適用する-これを行うと、Backboneが提供するイベントシステムが完全にバイパスされますが、これは奇妙に思えます。
Backboneは、すべてのイベントが適用された後にjQueryコードを実行する方法を提供しますか?