0

所以我一起使用 require.js 和 knockout.js。我有一个简单的页面来收集用户。

这是代码:

cshtml 文件:

@section scripts{
    <script data-main="../Scripts/app/usermanagement/app.invite" src="../Scripts/lib/require.js"></script>
}
<div id="usermanagement-invite-view">
    <p>Enter all the users you would like to invite to this account. You will be able to set the permissions onces you have added them.</p>
    <span data-bind="text: ko.toJSON($data)"></span>
    <div data-bind="foreach: invitedUsers()">
        <div><span data-bind="text: firstName"></span></div>
        <div><span data-bind="text: lastName"></span></div>
        <div><span data-bind="text: emailAddress"></span></div>
    </div>
    <div>
        <input type="text" placeholder="First Name" data-bind="text: firstName" class="input" />
        <input type="text" placeholder="Last Name" data-bind="text: lastName" class="input" />
        <input type="email" placeholder="EmailAddress" data-bind="text: emailAddress" class="input" />
        <input type="button" value="Invite" data-bind="click: invite" class="submit" />
    </div>
</div>

这是 app.invite.js

requirejs.config({
    "baseUrl": "../Scripts/app/usermanagement",
    "paths": {
        "app.invite": "app.invite",
        "ko": "../../lib/knockout-2.2.1",
        "jquery": "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min",
        "toastr": "../../lib/toastr"
    }
});

// Load the main app module to start the app
require(["main.invite"], function (bs) { bs.run(); });

这是 main.invite.js:

define(['ko', 'inviteViewModel'], function (ko, inviteViewModel) {
    var
        run = function () {
            var vm = new inviteViewModel();
            ko.applyBindings(vm, document.getElementById('#usermanagement-invite-view'));
        };
    return {
        run: run
    };
});

这是邀请视图模型:

define('inviteViewModel', ['jquery', 'ko', 'toastr', 'model.user'], function ($, ko, toastr, User) {

    return function inviteViewModel() {
        var self = this;

        self.firstName = ko.observable();
        self.lastName = ko.observable();
        self.emailAddress = ko.observable();

        self.invitedUsers = ko.observableArray();

        self.invite = function () {
            var newUser = new User();
            newUser.firstName(self.firstName());
            newUser.lastName(self.lastName());
            newUser.emailAddress(self.emailAddress());

            self.invitedUsers().push(newUser);
            console.log(self.invitedUsers());


        };

    }
});

出于某种原因,当我调用邀请函数时,代码显示我正在向集合添加一些内容,但 UI 没有更新。这是我做console.log时的样子。然而,这并没有显示价值

控制台日志

我究竟做错了什么?

4

1 回答 1

2

您需要push直接调用observableArrayKO 以便为您跟踪更改并更新 UI,因此您不需要括号:

self.invitedUsers.push(newUser);

另请参阅文档:

pop、push、shift、unshift、reverse、sort、splice

所有这些函数都相当于在底层数组上运行原生 JavaScript 数组函数,然后通知侦听器有关更改:

myObservableArray.push('Some new value')在数组末尾添加一个新项目

于 2013-06-20T21:18:38.327 回答