ラッパーやフレームワークを使用しないクリーンなバックボーンを使用しています。
そこで、いくつかの製品で管理するサイトを作成します。これには 2 つの動的ページがあります。
add.php
edit.php
これらのページは別個のバックボーン アプリケーションです。
どちらのページにも、製品カテゴリを表示する要素があります。通常はドロップダウン リストです。
次に、スクリプトのおおよその構造について説明します。簡単です。
js
+- models
| +- Category.js
| ...
+- collections
| +- Categories.js
| ...
+- views
| +- CategoriesView.js
| ...
CategoryView.jsには以下が含まれます。
App.Views.CategoriesViews = Backbone.View.extend({
template: _.template($('#tpl-categories').html()),
events: {
'change select': 'toggle'
},
initialize: function () {
_.bindAll(this, 'render');
this.collection.on('reset', this.render);
},
render: function () {
this.$el
.html(this.template({ collection: this.collection.toJSON() }));
return this;
},
toggle: function () {
// Some actions here
var catId = this.$el.children('select').val();
App.trigger('toggleCategories', catId);
}
});
ビューの初期化は次のようになります。
new App.Views.CategoriesViews({
el: $('#select-box-cats'),
collection: new App.Collections.Categories
});
この要素は両方のページ (add.php と edit.php) にあるため、両方でうまく機能します。
テンプレートの名前は両方のページで同じに設定できると想定しています。
<script type="text/template" id="tpl-categories">
それは良い習慣ではないと思いますが。
では、最後に私の質問です。
これらのページの 1 つがビューにイベント ハンドラーを追加する必要がある場合はどうなりますか。例えば:
initialize: function () {
_.bindAll(this, 'render', 'action');
this.collection.on('reset', this.render);
this.collection.on('request', this.action);
},
request
コレクションにイベントを追加しました。ただし、このイベントは別のページに存在するべきではありません。
何をすべきか?ページのニーズに対する変更を含む別のビュー ファイルを作成するには? しかし、これは DRY の原則に違反しており、大量のクライアント コードを生成します。