我有一个复杂对象的可观察数组。初始加载很好,所有预期的数据看起来都很好。现在我正在将新项目发布到该数组。注意:可观察数组是通过 ASP.NET ajax web api 调用加载的。
就将新项目保存到数据库而言,发布一个新项目可以正常工作,但是我的 DOM 没有用新项目更新,我不知道我错过了什么。
这是整个 ViewModel
function ClientList() {
//data
var self = this;
self.initialized = ko.observable(false);
self.clients = ko.observableArray();
self.userId = ko.observable("");
self.name = ko.observable("");
self.logo = ko.observable("");
self.projects = ko.observableArray();
self.clientAddress = ko.observableArray();
self.addClient = function () {
var client = {
UserId: self.userId,
Name: self.name,
Logo: self.logo,
}
client = ko.toJSON(client);
lucidServer.addClient(client);
self.clients.push(client);
}.bind(self);
(function () {
$.ajax({
url: lucidServer.getClients(1),
success: function (data) {
ko.mapping.fromJS(data, {}, self.clients);
self.initialized(true);
}
});
})();
};
function IncompleteStoriesList() {
//data
var self = this;
self.initialized = ko.observable(false);
self.stories = ko.observableArray();
(function () {
$.ajax({
url: lucidServer.getIncompleteStory(1),
success: function (data) {
ko.mapping.fromJS(data, {}, self.stories);
self.initialized(true);
}
});
})();
};
function ViewModel() {
var self = this;
self.clientList = new ClientList();
self.storyList = new IncompleteStoriesList();
}
ko.applyBindings(new ViewModel());
这是我正在执行 POST 的特定片段(在 ClientList() 函数中)。
self.addClient = function () {
self.client = {
UserId: self.userId(),
Name: self.name(),
Logo: self.logo(),
}
//make client object to send to server
var client = ko.toJSON(self.client);
lucidServer.addClient(client);
//push the self.client to the observablearray of clients
self.clients.push(self.client);
}.bind(self);
我验证了它是位于客户端变量中的 JSON,并且没有抛出错误消息,所以我很困惑。添加项目并刷新整个页面后,它将显示在列表中。
编辑:这是相关的html:
<form data-bind="submit: clientList.addClient">
<div>
<label>userId</label>
<input type="text" data-bind="value: clientList.userId" />
</div>
<div>
<label>name</label>
<input type="text" data-bind="value: clientList.name" />
</div>
<div>
<label>logo</label>
<input type="text" data-bind="value: clientList.logo" />
</div>
<button type="submit">Add</button>
</form>
<!-- ko ifnot: clientList.initialized -->
<span>Loading...</span>
<!-- /ko -->
<ul data-bind="template:{name: 'clientList', foreach:clientList.clients}">
</ul>
外部模板如下所示:
<div id="clientListOutput">
<li><span data-bind="text: name"></span>
<div data-bind="template: {foreach: clientAddress}">
<span data-bind="text: city"></span>
<span data-bind="text: state"></span>
</div>
<hr />
<ul data-bind="template: {foreach: projects}">
<li>
<span data-bind="text: name"></span>
<span data-bind="text: summary"></span>
<span data-bind="text: description"></span>
</li>
</ul>
</li>