【问题标题】:knockout.js data-bind 'with' conflicts with jQuery change eventknockout.js 数据绑定 'with' 与 jQuery 更改事件冲突
【发布时间】:2012-05-30 13:35:02
【问题描述】:

由于某种原因,当我使用 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>

【问题讨论】:

    标签: data-binding knockout.js onchange


    【解决方案1】:

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

    一些替代方案:

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

    【讨论】:

    • 是的,它做到了...这是我添加的内容:this.GraduationClass.GraduationClassId.subscribe(function() { alert('hi'); });
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-11-22
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 2011-09-08
      • 1970-01-01
      相关资源
      最近更新 更多