我有以下html视图模板,其中包含一个表:
<script id="user-home-main-table-template" type="text/template">
<table class="table">
<thead>
<tr>
<th>Club</th>
<th>Delete?</th>
</tr>
</thead>
<tbody>
<% for(var i=0; i
<teams.length
; i++) { %>
<tr>
<td>
<a href='/users/<%=user._id%>/teams/<%= teams[i]._id%>/teamDashboard'>
<%= teams[i].club %>
</a>
</td>
<td>
<a href='/users/<%=user._id%>/teams/<%= teams[i]._id%>/deleteTeam'>
delete
</a>
</td>
</tr>
<% } %>
</tbody>
</table>
</script>
我想更改它,以便在Backbone中触发事件而不是直接向服务器发出请求:
<script id="user-home-main-table-template" type="text/template">
<table class="table">
<thead>
<tr>
<th>Club</th>
<th>Delete?</th>
</tr>
</thead>
<tbody>
<% for(var i=0; i
<teams.length
; i++) { %>
<tr>
<td>
<a href='/users/<%=user._id%>/teams/<%= teams[i]._id%>/teamDashboard'>
<%= teams[i].club %>
</a>
</td>
<td>
<a href='make a request to Backbone when deleting team'>
delete
</a>
</td>
</tr>
<% } %>
</tbody>
</table>
</script>
这是我的Backbone视图代码:
var UserHomeMainTableView = Backbone.View.extend({
tagName: "div",
events: {},
initialize: function () {
this.bind();
},
render: function () {
var userHomeMainTableTemplate = document.getElementById('user-home-main-table-template').innerHTML;
this.$el.html(_.template(userHomeMainTableTemplate)());
console.log('userHomeMainTableTemplate rendered');
return this;
}
});
如何在我的Backbone视图中触发与具有正确ID的团队相关的事件?我需要向Backbone发送要删除的团队ID。
答案 0 :(得分:1)
在UserHomeMainTableView's
events
哈希中,您可以添加click <your_element_selector>
属性,其值为eventHandlerName
,例如
var UserHomeMainTableView = Backbone.View.extend({
tagName: "div",
events: {
'click .table span' : 'deleteTeamById'
},
initialize: function () {
this.bind();
},
render: function () {
var userHomeMainTableTemplate = document.getElementById('user-home-main-table-template').innerHTML;
this.$el.html(_.template(userHomeMainTableTemplate)());
console.log('userHomeMainTableTemplate rendered');
return this;
},
deleteTeamById: function (event) {
//using event fetch the target from that fetch team or user id whatever you need, make sure you add it as an attribute in template and use it
var teamId = $(event.currentTarget).attr('data-team-id');
//Your logic to delete team
}
});
模板可以更改为:
<script id="user-home-main-table-template" type="text/template">
<table class="table">
<thead>
<tr>
<th>Club</th>
<th>Delete?</th>
</tr>
</thead>
<tbody>
<% for(var i=0; i
<teams.length
; i++) { %>
<tr>
<td>
<a href='/users/<%=user._id%>/teams/<%= teams[i]._id%>/teamDashboard'>
<%= teams[i].club %>
</a>
</td>
<td>
<span data-team-id="<%= teams[i]._id%>">
delete
</span>
</td>
</tr>
<% } %>
</tbody>
</table>
</script>
查看this示例。