observableArray not updating the UI

2019-08-15 16:54发布

I am facing a problem that the UI only updates with correct data after a refresh of the page. I am coming from here observableArray is not defined

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);
                    widget.anotherObservableArray = ko.observableArray();

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

                    }
                    console.log(myKoObservableArray());
                    this.myKoObservableArray = myKoObservableArray;
                };
            }
        }
    }
);

My 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: myKoObservableArray">
        <li>
            <span data-bind="text: prodName"> </span> //this changes only after a refresh
        </li>
    </ul>
</div>

The data-bind="text: prodName" changes value only after a refresh of the page.

1条回答
Root(大扎)
2楼-- · 2019-08-15 17:35

Create the array once in onLoad, and then just update it. Don't keep creating it each time.

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

                    // empty the array
                    widget.myKoObservableArray([]);

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

                    }
                    console.log(widget.myKoObservableArray());
                };
            }
        }
    }
);
查看更多
登录 后发表回答