I've checked this post, and this one, and this one , and numerous others and none of the solutions seem to help me at all. All I'm trying to do is replace the contents of a view with an array of html. Each element in the array is created by using the underscore templating engine. Here's my code:
The Template:
<script type="text/template" id="radioItemTemplate">
<li>
<div class="button price <% if(enabled){%>enabled<%}%>">$<%=price%></div>
<div class="title name"><%=name%></div>
</li>
</script>
The Javascript:
iHateThisView = Backbone.View.extend({
template: _.template($("#radioItemTemplate").html()),
events:{
"click .price": "_onRadioItemClick"
},
radioItems: null,
radioItem: null,
initialize: function (options) {
this.radioItems = options.radioItems;
this.radioItem = options.radioItem;
},
render: function () {
trace("rendering");
var radioItems = this.radioItems.first(3);
var activeRadioItem = this.radioItem.get('name');
var result = [];
var scope = this;
_.forEach(radioItems, function (radioItem) {
var option = {
name: radioItem.get('name'),
price: radioItem.get('price'),
enabled: activeRadioItem == radioItem.get('name')
};
result.push(scope.template(option));
});
//THE TRICKY ZONE -START
this.$el.html(result);
//THE TRICKY ZONE -END
return this;
},
_onRadioItemClick: function (event) {
$el = this.$el;
var clickedName = $el.find('price');
console.log('clickedName');
}
});
Aside from it wrapping my html with a <div>
this does exactly what I want on the first render. However if I called my render function again, none of the events work. So based on all my readings, I figured this.delegateEvents()
should fix the loss of events, so I tried this:
//THE TRICKY ZONE -START
this.$el.html(result);
this.delegateEvents();
//THE TRICKY ZONE -END
Which from what I can tell did nothing. On the first render when I click on the radioItems I'd get my console.log
, but again not after a re-render
so then I read that I might have to do this:
//THE TRICKY ZONE -START
this.$el.html(result);
this.delegateEvents(this.events);
//THE TRICKY ZONE -END
Which also did nothing.
So then I tried a different method:
//THE TRICKY ZONE -START
this.setElement(result);
this.delegateEvents(); //with and without this line
//THE TRICKY ZONE -END
This added only the first item in the array, and the events didn't work even on the first render.
Please restore my sanity guys, I don't what else to do.