アイテムのリストとプレースホルダーの「新しい」アイテムが表示されるBackbone.jsを使用してアプリケーションを構築しています。コンテナは、すべてのサブビューを保持してレンダリングするビューです。
しばらく検索しましたが、機能させることができません。問題は、テンプレートの [追加] ボタンがイベントを発生させないことです。後でレンダリングが行われるため、イベントが割り当てられていないと思います。他の投稿を読むと、これは Backbone.js で処理する必要がありますが、そうではないようです。後でjQueryイベントハンドラーを追加するrender()
と仕事ができますが、それは解決策にはならないと思います。
ビューの関連コードは次のとおりです。
template: _.template($("#template-time-new").html()),
events: {
'click #btn-new-time': 'onButtonNewClick'
},
render: function() {
this.$el.html(this.template());
return this;
},
onButtonNewClick: function() {
return false; // in this case: prevent page reload
}
私のテンプレート(翡翠):
script(type="text/template", id="template-time-new").
<h3>
<label for="new-time-name" class="muted">Name:</label>
<input id="new-time-name" type="text">
</h3>
<div class="time-inner">
<form class="form-horizontal">
<label for="new-time-start" class="muted">From:</label>
<input id="new-time-start" type="datetime-local">
<label for="new-time-end" class="muted">to</label>
<input id="new-time-end" type="datetime-local">
<button class="btn" id="btn-new-time">
Add
</button>
</form>
</div>
編集:
親ビューのコードは次のとおりです。
initialize: function() {
this.newView = new TimeSpanNewView; // <---- the view that is not really working
this.render();
// bind event handlers
this.collection.on('all', this.render, this);
// fetch data
this.collection.fetch();
},
render: function() {
var self = this;
self.$el.empty();
if ( self.collection.length > 0 ) {
self.collection.each(function(timespan) {
var subView = new TimeSpanView({ // sub views for the items, everything fine here
model: timespan
});
subView.render()
self.$el.append(subView.el);
});
} else {
self.$el.text("Nothing found.");
}
self.$el.append(self.newView.render().el);
return self;
}