0

Using Knockout.js 3.2.0, I've been fighting to get an observableArray successfully bound, and have narrowed it down to the with binding. Foreach has no problems, but with throws the error Uncaught ReferenceError: Unable to process binding "with: function (){return contactLists }".

Can anyone help me understand what's going on?

This works:

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

This doesn't:

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

ko.observableArray and applyBindings declarations:

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);

Many thanks for any help!

4

1 回答 1

0

“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);

见笔

于 2014-12-19T17:44:29.123 回答