<div class="container"> // this is the parent div template (already existing in the DOM prior to instantiating the View
HTML 模板:
<div id="measure-cid1"> // the number is dynamic
<div class="row-fluid">
<div class="remove-measure-rep"><i class="icon-minus"</i></div>
</div>
…other stuff…
</div>
<div id="measure-cid2">
<div class="row-fluid">
<div class="remove-measure-rep"><i class="icon-minus"</i></div>
</div>
…other stuff…
</div>
… multiple other 'measure-cid*'s
// remaining portion from the parent div template
</div>
BB JS 视图:
define([…], …){ //using require
return Backbone.View.extend({
// I can not define the el here, as it is dynamic, so I have to set it in the init
events : {
'click .remove-measure-rep' : 'removeRepresentation',
'click' : 'removeRepresentation'
},
initialize: function(options){
if (options) {
//passing options.* to this view as this.*
for (var key in options) {
this[key] = options[key];
}
console.log(this.el); // I get `<div></div>`
this.el = '#measure-rep-'+this.measureRepModel.cid;
console.log(this.el); // This returns `#measure-rep-c28`
this._ensureElement();
console.log(this.el); //This returns `undefined`
this._ensureElement($('#measure-rep-'+this.measureRepModel.cid));
console.log(this.el); //this returns `<div></div>`
this.setElement($('#measure-rep-'+this.measureRepModel.cid));
console.log(this.el); // this returns `undefined`
}
//Dispatch listeners
…
//Binding
this.model.bind('change', _.bind(this.render, this));
this.render();
},
render: function(){
// I attach the template to its parent div
var compiledTemplate = _.template( MeasureRepTemplate, measureRepTemplateParamaters );
// put in the rendered template in the measure-rep-container of the measure
$(this.repContainerEl).append( compiledTemplate );
},
removeRepresentation: function(ev){
console.log('getting here');
}
})
};
在阅读了el
在 init 之前甚至作为临时持有者创建之后,我无法弄清楚如何捕获 class 的点击'.remove-measure-rep'
。我还在模板上验证了该类remove-measure-rep
在模板中,而不是在其他地方,因为似乎其他关于未捕获事件的 SO 问题与仅在自己的模板中查找类或 ID 的视图有关。视图应该创建 HTML,并将其添加到 DOM。
如何让视图访问点击事件?,因为当我将 el 设置为 init 中的不同值时它没有注册。我分别尝试了其中的每一个,但仍然无法正常工作。它是否与在 div 中设置模板然后尝试将模板中的元素绑定到视图有关?