Knockout JS array empty or can't retrieve values?

让人想犯罪 __ 提交于 2019-12-18 09:29:12

问题


I have a Javascript ajax function that retrieves comments from the server(Note: I'm new to Knockout JS):

function Comments() {
var self = this;
self.commentArray = ko.observableArray();
self.getNewerComments = function(lastCommentId) {
    pageId = $('body').attr('id');
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "Controller/getNewerComments/" + pageId + "/" + lastCommentId,


    })
            .done(function(data) {

                self.commentArray = ko.observableArray(data);
                alert(self.commentArray[0].authorName);


            })

}

}

With the alert I can see that the value is indeed set there, at the start of my JS file I have the following code:

var comments = new Comments();
ko.applyBindings(comments);
comments.getNewerComments(0);

And in the html file:

<!-- ko foreach: commentArray -->
<li>Item <span data-bind="text: $index"></span></li>
<!-- /ko -->
</div>

However, nothing shows up in the html document, not even the "Item" text, which indicates the array has 0 length. What's the problem here? Why can't I use the array values?

Thank you.


回答1:


You should use existing observable array (which was bound) instead of creating a new one:

.done(function(data) {
   self.commentArray(data);
   alert(self.commentArray[0].authorName);
 })



回答2:


You're setting the observable array twice. At the start and again at the Ajax call. Once you have the model built and apply bindings, no need to mess with observables again. It's done. Any changes to your data object tied to the model will be handled.



来源:https://stackoverflow.com/questions/26527529/knockout-js-array-empty-or-cant-retrieve-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!