2012-05-30 33 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