我已经编写了Backbone视图 - ListView并希望在其中显示表格。对于单个表行,还有另一个视图 - EmployeeView。
我正在使用function-deleteEmployee()在模板内部的删除按钮上绑定click事件,但看起来事件不起作用且函数未被调用。
这是代码块 -
app.ListView = Backbone.View.extend({
tagName : 'table',
render : function() {
$(this.el).append("<tr><td>Employee</td><td>Designation</td><td>Edit</td><td>Delete</td></tr>");
app._collection.each(this.renderEmployee, this);
$('#main').append(this.$el.html());
// main is the main div tag inside body
},
renderEmployee : function(model) {
var employeeView = new app.EmployeeView({
model : model
});
$(this.el).append(employeeView.render().el);
},
initialize : function() {
app._collection.on('reset', this.render, this);
app._collection.fetch();
console.log(JSON.stringify(app._collection));
}
});
app.EmployeeView = Backbone.View.extend({
tagName : 'tr',
template : _.template($("#employee-template").html()),
events : {
"click input#editemp" : 'editEmployee',
"click input#deleteemp" : 'deleteEmployee'
},
render : function() {
console.log('inside employeeView');
console.log(JSON.stringify(this.model));
this.$el.html(this.template(this.model.toJSON()));
this.delegateEvents();
return this;
},
editEmployee : function() {
},
deleteEmployee : function() {
alert('Hello');
}
});
这是模板 -
<script type="text/template" id="employee-template" >
<td><%= name %></td>
<td><%= designation %></td>
<td><input id="editemp" type="button" value="Edit"/></td>
<td><input id="deleteemp" type="button" value="Delete"/></td>
</script>
答案 0 :(得分:0)
使用类来标识可重复元素而不是id(因为id标识单个唯一元素)。
events : {
"click .editemp" : 'editEmployee',
"click .deleteemp" : 'deleteEmployee'
}
<script type="text/template" id="employee-template" >
<td><%= name %></td>
<td><%= designation %></td>
<td><input class="editemp" type="button" value="Edit"/></td>
<td><input class="deleteemp" type="button" value="Delete"/></td>
</script>
在这里更新了JSFiddle https://jsfiddle.net/2yqrh1yx/11/