2013-07-25 235 views
0

在underscore.js模板中,是否有方法從點擊事件中獲取模板的數據?例如:下劃線/骨幹模板事件

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!"); 
       } 
      }); 

然後在視圖骨幹:

events: { 
     'click #search-results li': function(data){ 'the data of the `result` that was passed to the template in the each'} 
    }, 

回答

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對象,而不是將其存儲在,你可以做類似於CanJS's element callback呢,在這裏你存儲對象與jQuery.data元素上的東西的DOM:

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')在回調中檢索它。

+0

你只是打敗了我...雖然我沒有肉體出去。 – Jack