Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

javascript - Knockout JS array empty or can't retrieve values?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...