observableArray is not defined

2019-09-02 05:00发布

问题:

I am working in a client development environment and have to adhere to their coding standards. I have the following JS and HTML. My observableArray is coming as not defined. I am not able to get it working. Even the console.logs are printing the correct values.

Please don't worry about ko.applyBindings. It is taken care of.

My JS Code:

define(
    ['knockout'],
    function (ko) {
        "use strict";
        return {
            onLoad: function (widget) {
                widget.getDetails= function (prod) {
                    var abc = prod.DetailsNumbers();
                    console.log(abc);
                    var someArray= [];
                    someArray= abc.split(',');
                    //console.log(someArray);
                    var anotherObservableArray = ko.observableArray();

                    for (var i = 0; i < someArray.length; i++) {
                        var temp = {
                            "prodName": ko.observable(someArray[i])
                        };
                        anotherObservableArray.push(temp);
                    }
                    console.log(anotherObservableArray());
                };
            }
        }
    }
);

My HTML Code:

<div id="someId">
    <table>
        <tbody>
            <tr>
                <td>Button Here</td>
                <td><button data-bind="click: getDetails(product())">Click me</button></td> 
            </tr>// this here is working fine
        </tbody>
    </table>
    <ul data-bind="foreach: anotherObservableArray"> // this doesnt work
        <li>
            <span data-bind="text: prodName"> </span>
        </li>
    </ul>
</div>

anotherObservableArray is not defined

回答1:

You don't expose anotherObservableArray outside the function scope you declare it in. Basically your code is of this format:

{
  onLoad: function (widget) {
    widget.getDetails = function (prod) {
      var anotherObservableArray = ko.observableArray();
      // push some items into the array
      console.log(anotherObservableArray());
    };
  }
}

You somehow need to expose the anotherObservableArray outside the function. For example:

{
  onLoad: function (widget) {
    widget.getDetails = function (prod) {
      var anotherObservableArray = ko.observableArray();
      // push some items into the array
      console.log(anotherObservableArray());
      this.anotherObservableArray = anotherObservableArray; // Expose it on the function
    };
  }
}


回答2:

Move var anotherObservableArray = ko.observableArray(); to your VM definition and ensure it's exposed (i.e. "public"). I am imagining you do have something like this:

var vm = {
    // ...
    // most likely you are exposing getDetails() already 
    // .... 

    anotherObservableArray: ko.observableArray()
};

// ...

ko.applyBindings(vm);