observableArray未定义

时间:2016-04-05 15:27:38

标签: javascript jquery html knockout.js

我在客户端开发环境中工作,必须遵守他们的编码标准。我有以下JS和HTML。我的observableArray未定义。我无法让它发挥作用。甚至console.logs也会打印正确的值。

请不要担心ko.applyBindings。这是照顾。

我的JS代码:

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

我的HTML代码:

<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

2 个答案:

答案 0 :(得分:1)

var anotherObservableArray = ko.observableArray();移至您的VM定义并确保其已公开(即“公开”)。我想你确实有这样的事情:

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

    anotherObservableArray: ko.observableArray()
};

// ...

ko.applyBindings(vm);

答案 1 :(得分:1)

您不会在您声明的函数范围之外公开anotherObservableArray。基本上您的代码采用以下格式:

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

您需要在函数外部公开anotherObservableArray。例如:

{
  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
    };
  }
}