私は、ある種のアプリ コレクションのような比較的大きなアプリケーションに取り組んでいます。
私のアプリはすべて、基本レイアウトとネストされたビューをロードするブートストラップ ビューを取得しました。
ビューにシングルトン パターンを実装し始めました。
var SomeView = Backbone.View.extend({});
if (SomeView._instance) return SomeView._instance;
SomeView._instance = new SomeView();
return SomeView._instance;
ここで、異なるアプリ (ビュー) を切り替えると、イベント システムが壊れていると言いました。これは実際には非常に論理的で、最終的にドキュメントからビューを削除します。しかし、常に新しい視点を構築することには、ある種の抵抗があります。これはまったく効果がありません。すべてを再読み込み (データ) して再構築する必要があります。
イベントをキャッシュされたビューに再バインドする方法はありますか、それともこの考え全体が悪いので、ビューを再構築する必要があることを受け入れる必要がありますか?
アップデート:
define(['jquery', 'underscore', 'backbone', 'views/settings/profile'], function($, _, Backbone, ProfileSettingsView) {
var ContentView = Backbone.View.extend({
tagName: "div",
className: "content well",
initialize: function() {
this.on('change:section', this.change, this);
this.views = {};
this.views.profile = new ProfileSettingsView();
},
render: function() {
this.$el.empty();
return this;
},
events: {
"click": "click"
},
// the router triggers this one here
change: function(query) {
console.log(query);
// if I uncomment this then nothing is rendered at all
//this.$el.detach();
var el;
if (query === 'profile') {
el = this.views.profile.render().el;
} else {
this.$el.empty();
}
if (el) {
this.$el.empty().append(el);
}
},
click: function(e) {
console.log('clicked, content should disapear');
}
});
if (ContentView._instance) return ContentView._instance;
ContentView._instance = new ContentView();
return ContentView._instance;
});
jQuery の .xml の使用方法について少し混乱していますdetach()
。公式ドキュメントのデモを見て.detach()
、jQuery オブジェクトを呼び出すだけでは不十分であることがわかりました。.detach
jQuery オブジェクトのように見え、バインドされたイベントを含む新しいオブジェクトを返します。detach()
これについての難しいことは、どこかのこのリターンを保存しなければならないことです。そして今、私は目を通していません。Backbone.View
を使用していくつかの例を検索しdetach()
ますが、それは具体的なものだと思います....
更新 2:
はい!イベントを保存してからDOMに再挿入する代わりに、回避策を見つけました。this.delegateEvents()
すべてのイベントを再バインドするために呼び出すことができます。これは本当に単なる回避策であり、誰かが私に例を提供できれば幸いです:)