【发布时间】:2013-07-11 18:52:30
【问题描述】:
我正在使用 Backbone.js 构建一个应用程序,其中显示项目列表和占位符“新”项目。容器是一个包含所有子视图并渲染它们的视图。
我已经搜索了一段时间,但无法让它工作。
问题是模板中的“添加”按钮没有触发事件。我猜这是因为渲染发生在稍后的时间点,所以没有分配事件。阅读其他帖子应该由 Backbone.js 处理,但似乎并非如此。在render() 之后添加一个 jQuery 事件处理程序可以完成这项工作,但我认为这不是解决方案。
下面是视图的相关代码:
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;
}
【问题讨论】:
-
工作正常:jsfiddle.net/ambiguous/MNJd5 你有什么不同的做法?而
<button>真的应该是<button type="button">。 -
没什么,这就是我提出这个问题的原因。尝试添加 this.delegateEvents(); [就像作为消失的答案发布的那样],现在它工作得很好。
-
您使用的是什么版本的 Backbone?
-
我会要求更多代码。我有类似的问题,所以我想看看你如何在父视图中使用你的视图。
-
v1.0.0,来自网站的当前版本。
标签: javascript templates backbone.js underscore.js backbone-events