2013-05-16 2 views
0

내 backbone.js 앱에는 항목 모음이 있습니다. 컬렉션 및 각 항목에 대한보기가 예상대로 렌더링됩니다.백본보기의 이벤트

각 항목에는 두 가지 조치가 있습니다. A와 B가 있습니다. A 및 B 조치를 처리 할 수 ​​있도록 ItemView 클래스의 이벤트 리스너를 연결하려면 어떻게합니까?

window.SourceListItemView = Backbone.View.extend({ 
tagName: "li", 

initialize: function() { 
    this.model.bind("change", this.render, this); 
    this.model.bind("destroy", this.close, this); 
}, 

render: function() { 
    $(this.el).html(this.template(this.model.toJSON())); 
    return this; 
}, 

events: { 
    "click .action_a": "doA", 
    "click .action_b": "doB" 
}, 

doA: function(event) { 
    alert("A clicked for " + JSON.stringify(event)); 
}, 


doB: function(event) { 
    alert("B clicked for " + JSON.stringify(event)); 
} 

});

이 줄은 문제가 될 것으로 보인다

<a href="#sources/<%=id %>" class="source thumbnail plain" style="text-align: center;"> 
    <h4><%= name %></h4> 
    <button class="btn btn-primary action_a"> A</button> 
    <button class="btn btn-info action_b"> B</button> 
</a> 
+0

가 문제를 이해하려고 노력. doA, doB는 해고되지 않았나요? 너 문제 야? – Protostome

+0

예 문제가 – VNVN

답변

1

ItemView의 템플릿 :

$(this.el).html(this.template(this.model.toJSON())); 

나는 그것을 사용하여이 일을 가지고 : 나는의 번호를 변경

this.$el.html(test(this.model.toJSON())); 

주 다른 것들은 로컬로 작업 할 수 있고 그렇지 않을 수도 있습니다. 그녀의 문제.

  • 보기에서 템플릿을 지정해야합니다.
  • <a> 태그에 버튼이 포함되어 있습니다.
  • JSON.Stringify (event) do 함수를 변경해야합니다.

근무 코드 :

<html> 

     <script src="./jquery.js"></script> 
     <script src="./underscore.js"></script> 
     <script src="./backbone.js"></script> 

     <body> 
     </body> 

     <script> 
     window.SourceListItemView = Backbone.View.extend({ 
      tagName: "li", 

      initialize: function() { 
       this.model.bind("change", this.render, this); 
       this.model.bind("destroy", this.close, this); 
      }, 

      template: function(data) { 
      var compiled = _.template('<a href="#sources/<%=id %>" class="source thumbnail plain" style="text-align: center;"> <h4><%= name %></h4> </a> <button class="btn btn-primary action_a"> A</button> <button class="btn btn-info action_b"> B</button>'); 
      return compiled; 
      }, 

      render: function() { 
       var test = this.template(); 
       this.$el.html(test(this.model.toJSON())); 
       return this; 
      }, 

      events: { 
      "click .action_a": "doA", 
      "click .action_b": "doB" 
      }, 

      doA: function(event) { 
       alert("A clicked for " + JSON.stringify(event)); 
      }, 


      doB: function(event) { 
       alert("B clicked for " + $(event.srcElement).html()); 
      } 
     }); 

     testModel = new Backbone.Model({id: 1, name: 'Elias'}); 
     testRow = new SourceListItemView({model: testModel}); 
     $('body').append(testRow.render().$el); 
     </script> 
    </html> 
관련 문제