2012-05-30 30 views
4

由於某些原因,當我使用data-bind =「with:detailedStudent」時,jQuery change()綁定不會被調用。我動態地填充選擇選項,但我不確定這應該重要。這是一些我使用的只是儘量給怎麼回事的體面圖片代碼:knockout.js data-bind'with'與jQuery change事件衝突

var viewModel; 
$(document).ready(function() { 
    viewModel = new StudentViewModel(); 
    ko.applyBindings(viewModel); 

    // this change event is not getting called, but if i put the onchange directly into the html as an attribute, it works fine. 
    $("#accountDialog").find("#mySelect").change(function() { 
     alert('hi'); 
    } 
} 

function Student(data) { 
    var self = this;  
    ko.mapping.fromJS(data, {}, this);     
} 

function StudentViewModel() { 
    var self = this;  
    this.students = ko.observableArray([]);  
    this.detailedStudent = ko.observable(); 
} 

<div id="accountDialog" class="modal hide fade" data-bind="with: detailedStudent"> 
    <select id="mySelect" name="mySelect" data-bind="value: GraduationClassId"></select> 
</div> 

回答

5

with結合是一個包裝到template結合。它複製子元素並將其用作模板。所以,如果您的detailedStudent正在改變,那麼KO將在每次沒有附加事件處理程序時渲染新元素。

一些替代方案:

  • 使用綁定附加事件處理程序(可以使用event結合)
  • 創建manual subscription對你detailedStudent觀察到的,在視圖模型執行的動作(最好的選擇,如果您的操作不涉及DOM操作)
  • 嘗試使用委託事件處理程序,如jQuerys $.on()http://api.jquery.com/on/
+0

是的,這確實是......這是我補充的內容:this.GraduationClass.GraduationClassId.subscribe(函數(){ 警報( '你好'); }); –

0

如果操作不涉及DOM操作,那麼我同意RP尼邁耶手動訂閱是最好的選擇。

但是,通常我們會有一些事件與DOM操作,例如,設置jquery對話框/ datepicker插件到您的財產。我認爲自定義綁定將是最佳選擇。自定義綁定將與「with」綁定子句完美配合,以將事件處理程序設置爲任意的javascript函數。

你可以通讀這一點,它並不像看起來那麼難。 http://knockoutjs.com/documentation/custom-bindings.html