Backbone の学習を始めたばかりで、自分のコードにバグがあることに気付きましたが、その解決方法がわかりません。
ControlView でボタンがクリックされるたびに、そのボタンのクリックに関連付けられたビューが読み込まれます。すごい!ただし、ボタン (#button-1) をクリックした場合は、隣接するボタン (#button-2) をクリックし、最初のボタン (#button-1) を再度クリックします。これで、そのビューの 2 つのインスタンスが作成されます。重複したイベントにつながります。つまり、そのビューでフォームを送信するたびに、n + 2 個の HTTP リクエストを取得します。
最初の初期化時にビューを作成するようにコードを調整しました。これらは必要になるたびにレンダリングされます。これが最善の方法ですか?
どうもありがとう!
var ControlView = Backbone.View.extend({
el: $(".btn-group"),
active: 'btn-primary',
initialize: function()
{
_.bindAll(this, 'account', 'password');
this.account();
},
events: {
"click button.account" : "account",
"click button.password" : "password"
},
account: function()
{
this.reset();
this.state("button.account");
profile.fetch({
success: function()
{
AccountView.render();
}
});
},
password: function()
{
this.reset();
this.state("button.password");
PasswordView.render();
},
state: function(element)
{
$(element).addClass(this.active);
},
reset: function()
{
$(this.el).find("button").removeClass(this.active);
},
});
AccountView = new AccountView({model:profile});
PasswordView = new PasswordView({model:user});
ControlView = new ControlView;