【问题标题】:Knockout.js foreach binding works, but with binding does notKnockout.js foreach 绑定有效,但绑定无效
【发布时间】:2015-02-18 15:57:19
【问题描述】:

使用 Knockout.js 3.2.0,我一直在努力争取成功绑定 observableArray,并将其缩小到 绑定。 Foreach没有问题,但是with抛出错误Uncaught ReferenceError: Unable to process binding "with : function (){return contactLists }".

谁能帮我理解发生了什么?

这行得通:

<!-- ko foreach: contactLists -->
    <p data-bind="text: title"></p>
<!-- /ko -->

这不是:

<!-- ko with: contactLists -->
    <p data-bind="text: title"></p>
<!-- /ko -->

ko.observableArrayapplyBindings 声明:

var viewModels = {
        contactLists: ko.observableArray([new ContactList({title: "This Is List #1", subCount: 4321}), new ContactList({title: "List #2", subCount: 9876}), new ContactList({title: "jList #3", subCount: 1234})])
    }

    ko.applyBindings(viewModels);

非常感谢您的帮助!

【问题讨论】:

    标签: javascript data-binding knockout.js single-page-application knockout-3.0


    【解决方案1】:

    “with”绑定不适用于数组。您必须指定要工作的元素。示例:

    <!-- ko foreach: contactLists -->
      <!-- ko with: data -->
        <p data-bind="text: gender"> </p> 
      <!-- /ko -->
    <!-- /ko -->
    
    
    function ContactList(data) {
      this.title = data.title;
      this.subCount = data.subCount;
    }
    
    var viewModels = {
      contactLists: ko.observableArray([
        {title: "This Is List #1", data: { subCount: 4321, gender: "male"}},
        {title: "List #2", data: { subCount: 5321, gender: "female"}},
        {title: "jList #3", data: { subCount: 1221, gender: "any"}}])
    }
    
    ko.applyBindings(viewModels);
    

    See the Pen

    【讨论】:

    • 根据您的建议,我能够让它工作。我不敢相信我错过了。不错的收获!
    猜你喜欢
    • 2012-02-11
    • 1970-01-01
    • 2012-07-14
    • 2016-08-25
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多