0
votes

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!

1

1 Answers

0
votes

The "with" binding doesn't work with arrays. You have to specify the element to work. Example:

<!-- 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