0

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'}
    },
4

1 回答 1

2

过去我所做的是将我想要的数据粘贴在data-元素的属性中,如下所示:

var list =_.template("<ul>
    <% _.each(results, function(result){  %>
        <li data-foo=\"<%= result.foo %>\"><%= result.formatted_address %></li>
    <% })%>
</ul>");

在回调中,我可以像这样检索它:

'click #search-results li': function(ev){
    var foo = $(ev.currentTarget).data('foo');
}

但是,如果您需要访问整个result对象,而不是将其存储在 DOM 中,您可以执行类似于CanJS 的元素回调所做的事情,将对象存储jQuery.data在元素上:

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]);
});

然后使用回调在回调中检索它$(ev.currentTarget).data('result')

于 2013-07-25T13:43:48.873 回答