Reputation: 4084
In underscore.js templates, is there a way to get the data of the template from a click event? For example:
geocoder.geocode({
'address' : $(this.el).find("input[name=locationSearchText]").val()
}, function(results, status) {
if (results && status && status == 'OK') {
this.results = results;
var list =_.template("<ul><% _.each(results, function(result){ %><li><%= result.formatted_address %></li><% })%></ul>");
$el.find("#search-results").html(list);
}else{
alert("SOMETHING WENT WRONG!");
}
});
And then in backbone on the view:
events: {
'click #search-results li': function(data){ 'the data of the `result` that was passed to the template in the each'}
},
Upvotes: 0
Views: 166
Reputation: 11383
In the past what I've done is stick the data I want in a data-
attribute of the element, like this:
var list =_.template("<ul>
<% _.each(results, function(result){ %>
<li data-foo=\"<%= result.foo %>\"><%= result.formatted_address %></li>
<% })%>
</ul>");
And in the callback I could retrieve it like this:
'click #search-results li': function(ev){
var foo = $(ev.currentTarget).data('foo');
}
But if you need to access the whole result
object, rather than storing it in the DOM you could do something similar to what CanJS's element callback does, where you store the object with jQuery.data
on the element:
this.results = results;
var list =_.template("<ul><% _.each(results, function(result){ %><li><%= result.formatted_address %></li><% })%></ul>");
$el.find("#search-results").html(list).find('li').each(function(i, el) {
$(el).data('result', results[i]);
});
Then retrieve it in the callback using $(ev.currentTarget).data('result')
.
Upvotes: 2