2

私はこのHTMLを持っています:

<ul class="chat_list" 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>            
  </li>
</ul>

そしてこのJavaScript:

function ChatListViewModel(chats) {

   // 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.newChatText = ko.observable();

    self.addComment = function (chat) {
        var newComment = { CourseItemDescription: chat.NewCommentText(),
            ParentCourseItemID: chat.CourseItemID,
            CourseID: $.CourseLogic.dataitem.CourseID,
            AccountID: $.CourseLogic.dataitem.AccountID,
            SystemObjectID: $.CourseLogic.dataitem.CommentSystemObjectID,
            SystemObjectName: "Comments",
            UserName: chat.UserName
        };
        chat.CommentList.push(newComment);
        chat.NewCommentText("");
    };
}
ko.applyBindings(new ChatListViewModel(initialData)); 

デバッガーに入るchatと、関数のパラメーターがaddComment()チャット オブジェクトではなくフォーム要素であることがわかります。

なぜこうなった?

4

2 に答える 2

5

これは仕様によるものです。Knockout.js ドキュメントから:

この例に示すように、KO はフォーム要素をパラメーターとして送信ハンドラー関数に渡します。必要に応じてそのパラメーターを無視できますが、その要素への参照があると便利な場合の例については、ko.postJson ユーティリティのドキュメントを参照してください。

Serjioが指摘したように、カリー化を使用して追加のパラメーターを関数に渡すか、フォーム要素に関連付けられたコンテキスト全体を取得できるKnockout の Unobtrusive Event Handlingを利用できます。

self.addComment = function (form) {
    var context = ko.contextFor(form);
    var chat = context.$data;

    //rest of your method here
};
于 2012-07-03T02:54:05.290 に答える
5

KO行為のため。送信ハンドラーにチャット変数を渡すには、これを使用できます。

<ul class="chat_list" data-bind="foreach: chats">
    <li>
        <div class="chat_response" data-bind="visible: CommentList().length == 0">
            <form data-bind="submit: function(form){$root.addComment($data, form)}">
                <input class="comment_field" placeholder="Comment…" data-bind="value: NewCommentText" />
            </form>
        </div>            
    </li>
</ul>
于 2012-07-03T02:59:34.850 に答える