挖空.js数据绑定'with'与 jQuery 更改事件冲突



出于某种原因,当我使用 data-bind="with: detailedStudent" 时,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>

with绑定是template绑定的包装器。 它复制子元素并将它们用作模板。 因此,如果您的detailedStudent正在更改,则 KO 将在每次未附加事件处理程序时呈现新元素。

一些替代方案:

  • 使用绑定附加事件处理程序(可以使用event绑定)
  • 针对可观察detailedStudent创建手动订阅,并在视图模型中执行操作(如果您的操作不涉及 DOM 操作,则最佳选择)
  • 尝试使用委托的事件处理程序,如 jQuerys $.on() http://api.jquery.com/on/。

如果该操作不涉及 DOM 操作,那么我同意 RP Niemeyer,手动订阅是最佳选择。

但是,通常我们会有一些带有 DOM 操作的事件,例如,将 jquery 对话框/日期选择器插件设置为您的属性。我认为自定义绑定将是最佳选择。自定义绑定将与"with"绑定子句完美配合,以将事件处理程序设置为任意 JavaScript 函数。

你可以通读这篇文章,它并不像看起来那么难。http://knockoutjs.com/documentation/custom-bindings.html

最新更新