我必须使用backbone.js创建事件.Below是我的js代码
var Trainee = Backbone.Model.extend();
var TraineeColl = Backbone.Collection.extend({
model: Trainee,
url: 'name.json'
});
var TraineeView = Backbone.View.extend({
el: "#area",
template: _.template($('#areaTemplate').html()),
render: function() {
this.model.each(function(good){
var areaTemplate = this.template(good.toJSON());
$('body').append(areaTemplate);
},this);
return this;
}
});
var good = new TraineeColl();
var traineeView = new TraineeView({model: good});
good.fetch();
good.bind('reset', function () {
$('#myButtons').click(function() {
traineeView.render();
});
});
<div class = "area"></div>
<div class="button" id="myButtons">
<button class="firstbutton" id="newbutton">
Display
</button>
</div>
<script id="areaTemplate" type="text/template">
<div class="name">
<%= name %>
</div>
<div class="eid">
<%= eid %>
</div>
<div class="subdomain">
<%= subdomain %>
</div>
我点击显示按钮的o / p是 显示//这是一个按钮//
辛杜嘉 E808514 HPS
Shalini E808130 HBS
普里亚 E808515 HSG
现在从视图中我必须将更改事件绑定到模型..必须在视图上触发模型中的更改,才能在单击显示按钮上显示输出。
答案 0 :(得分:1)
这并不完全回答你的问题,但是:
如果受训者(我已将其重命名为受训者)是一个集合,您应该使用它来设置:
new TraineeView({collection: trainees});
然后在渲染中:
this.collection.models.each(function(trainee)
并且你可能不会将调用移动到视图之外,在路由器中可能:
trainees = new TraineeColl();
view = new TraineeView({collection: trainees});
trainees.fetch();
这样你的视图只会听模型。
您还应该将绑定部分移动到视图初始化方法
this.collection.bind('reset', function () {
this.render();
});
希望这有帮助。
答案 1 :(得分:0)
var TraineeView = Backbone.View.extend({
el: "#area",
initialize : function(options){ // you will get the passed model in
//options.model
var trainee = new TraineeColl();
trainee.fetch();
trainee.bind('reset change', this.render,this); //change will trigger render
// whenever any model in the trainee collection changes or is modified
}
template: _.template($('#areaTemplate').html()),
render: function() {
this.model.each(function(trainee){
var areaTemplate = this.template(trainee.toJSON());
$('body').append(areaTemplate);
},this);
return this;
}
});
var traineeView = new TraineeView({model: trainee});
});