所以我一起使用 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时的样子。然而,这并没有显示价值
我究竟做错了什么?