2011-10-03 224 views
0

單擊按鈕時事件如何觸發?骨幹js:事件未觸發問題

var test1 = new Test({ Name: "Test 1", id: 1 }); 
var test2 = new Test({ Name: "Test 2", id: 2 }); 
var test3 = new Test({ Name: "Test 3", id: 3 }); 
var tests = new TestCollection([test1, test2, test3]); 

TestView = Backbone.View.extend({ 
    initialize: function() { 
     this.render(); 
    }, 
    events: 
    { 
     "click .btn": "clickbtn" 
    }, 
    render: function() { 
     $("#tests_template").tmpl(tests.toJSON()).appendTo("#tests_list"); 
     this.delegateEvents(); 
     return this; 
    }, 
    clickbtn: function() { 
     alert('test'); 
    } 
}); 

var testView = new TestView(); 

<script id="tests_template" type="text/x-jquery-tmpl">  
    <li> 
    <b>${Name}</b><input type="button" id="btn" value="click" class="btn"/> 
    </li> 
</script> 

<ul id="tests_list"> 
</ul> 

回答

3

events聲明與您視圖的el元素一起使用。現在,您的代碼會直接將html輸出附加到視圖的el以外的其他位置。

這將解決它:


TestView = Backbone.View.extend({ 
    initialize: function() { 
     this.el = $("#tests_list"); 
     this.render(); 
    }, 
    events: 
    { 
     "click .btn": "clickbtn" 
    }, 
    render: function() { 
     var html = $("#tests_template").tmpl(tests.toJSON()); 
     $(this.el).append(html) 
     return this; 
    }, 
    clickbtn: function() { 
     alert('test'); 
    } 
});