4

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

2 回答 2

5

The with binding is a wrapper to the template binding. It copies off the child elements and uses them as the template. So, if your detailedStudent is changing, then KO will be rendering new elements each time that did not have the event handler attached to it.

Some alternatives:

  • use a binding to attach the event handler (can use event binding)
  • create a manual subscription against your detailedStudent observable and perform your action in the view model (best option, if your action does not involve DOM manipulation)
  • try to use a delegated event handler like jQuerys $.on() http://api.jquery.com/on/.
于 2012-05-30T13:57:55.033 回答
0

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

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

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

于 2013-06-03T09:45:51.787 回答