次のスクリーンショットは、サインインとサインアップを組み合わせたフォームを示しています。
をレンダリングするために、次のモジュールが使用されますAuthView
。
MyApp.module("User", function(User, App, Backbone, Marionette, $, _) {
User.AuthView = Marionette.ItemView.extend({
className: "reveal-modal",
template: "user/auth",
ui: {
signInForm: "#signin-form",
signUpForm: "#signup-form"
},
events: {
"focus input": "onFocus"
},
onFocus: function() {
console.log("Some input field has received focus.");
},
onRender: function() {
this.signInForm = new Backbone.Form({
schema: {
signInEmail: {
type: "Text",
title: "E-Mail address"
},
signInPassword: {
type: "Password",
title: "Password"
}
}
}).render();
this.ui.signInForm.prepend(this.signInForm.el);
this.signUpForm = new Backbone.Form({
schema: {
signUpEmail: {
type: "Text",
title: "E-Mail address"
},
signUpPassword: {
type: "Password",
title: "Password"
},
signUpPasswordConfirmation: {
type: "Password",
title: "Password confirmation"
}
}
}).render();
this.ui.signUpForm.prepend(this.signUpForm.el);
}
});
});
サブフォームがレンダリングされるたびに、各サブフォームの最初のフィールドに自動的にフォーカスするにはどうすればよいですか? 最初のフィールドsignInEmail
はsignInForm
およびsignUpEmail
ですsignUpForm
。イベント
を聞いてみました。focus input
このようなイベントは、入力フィールドの 1 つをクリックする前ではなく、クリックしたときにトリガーされます。
一方、現在の回答に触発されて、次のヘルパー関数を思いつきました。
focusFirstFormField: function(form) {
if (_.isUndefined(form)) {
throw "IllegalStateException: Form is undefined."
}
// TODO: AuthView does not focus first sign-in field.
var firstInput = form.find(':input:first');
if (_.isObject(firstInput)) {
if (firstInput.length > 0) {
firstInput = firstInput[0];
}
else {
throw "IllegalStateException: Form find returns an empty jQuery object."
}
}
_.defer(function() {
firstInput.focus();
});
}
とはいえ、まだまだ改善が必要です。