2013-07-25 2 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'); 
} 

하지만 당신은 오히려 당신이 CanJS's element callback 당신이 요소에 jQuery.data와 객체를 저장할 경우, 무엇을 비슷한 할 수있는 DOM에 저장하는 대신 전체 result 개체에 액세스해야하는 경우 : 다음

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

관련 문제