knockout throws消息:TypeError:<xxx>不是函数.这是什么意思?

lad*_*kie 3 javascript knockout.js

我有这个代码:

<ul id="chats" data-bind="foreach: chats">
   <li>
      <div class="chat_response" data-bind="visible: CommentList().length == 0">
        <form data-bind="submit: $root.addComment">
           <input class="comment_field" placeholder="Comment…" data-bind="value: NewCommentText" />
        </form>
      </div>
      <a class="read_more_messages" data-bind="visible: moreChats, click: showMoreChats">Read More Messages...</a>
   </li>
</ul>

function ChatListViewModel(chats) {
   // Data
   var self = this;

   self.chats = ko.observableArray(ko.utils.arrayMap(chats, function (chat) {
       return { CourseItemDescription: chat.CourseItemDescription,
           CommentList: ko.observableArray(chat.CommentList),
           CourseItemID: chat.CourseItemID,
           UserName: chat.UserName,
           ChatGroupNumber: chat.ChatGroupNumber,
           ChatCount: chat.ChatCount,
           NewCommentText: ko.observable("")
       };
   }));

   self.moreChats = ko.observable(true);

   self.showMoreChats = function () {
       var LastChatGroupNumber = self.chats()[self.chats().length - 1].ChatGroupNumber;

       $.ajax({
           url: $.CourseLogic.dataitem.GetMoreChatsUrl,
           data: "{chatGroupNumber: " + ko.toJSON(LastChatGroupNumber + 1) + "}",
           type: "post",
           contentType: "application/json",
           success: function (chats) {
               var chatList = self.chats();
               $.each(chats, function (index, chat) {
                   self.chats.push(chat);
               });
           }
       });
   }

}

ko.applyBindings(new ChatListViewModel(initialData));
Run Code Online (Sandbox Code Playgroud)

但是当调用showMoreChats函数时,我收到此错误:

Unable to parse bindings. Message: TypeError: CommentList is not a function; Bindings value: visible: CommentList().length == 0

这是什么意思?

ant*_*hok 7

并不是CommentList是未定义的,只是它不是一个可观察的(因此不是一个函数).原因是在你的ajax回调中,你只是按"原样"推送从服务器收到的"聊天"对象.你不是要创建一个名为CommentList的新的observableArray,但是你只是放置一个裸数组CommentList - 因此KO抛出了错误.

您需要进行与在viewmodel构造函数中构造self.chats时所做的相同的转换,例如:

$.each(chats, function(index, chat) {
    self.chats.push(
        {
            CourseItemDescription: chat.CourseItemDescription,
            CommentList: ko.observableArray(chat.CommentList),
            CourseItemID: chat.CourseItemID,
            UserName: chat.UserName,
            ChatGroupNumber: chat.ChatGroupNumber,
            ChatCount: chat.ChatCount,
            NewCommentText: ko.observable("")
        }
    );
});
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你还应该看看ko.mapping插件,它可以为你做这个转换.

编辑:此外,为了获得更好的性能,您不应将每个单独的项目推送到可观察数组中,而是将它们添加到一个批量操作中,例如:

self.chats( self.chats().concat( ko.utils.arrayMap(chats, function(chat) {
    return { /* ... same as before ... */ };
} ) );
Run Code Online (Sandbox Code Playgroud)