来自我的 viewModel 的 JS:
self.newInterests = ko.observableArray();
self.saveNewInterest = function () {
// construct data and send to server
var payload = {
// data defined here
};
var appendInterest = function(newInterest) {
self.newInterests().push(newInterest);
};
interestservice().addInterest(payload, appendInterest);
self.closeModal();
};
兴趣服务.add兴趣:
var addInterest = function (payload, callback) {
loadAnimate();
var options = {
url: apiEndpoint + 'interest',
type: 'POST',
dataType: 'json',
data: payload,
xhrFields: {
withCredentials: true
}
};
return $.ajax(options)
.done(function (response) {
toastr.success("Interest Added", "Success");
callback(response);
})
.fail(function (msg) {
toastr.error("Could not add interest.", "Error");
}).complete(function () {
loadComplete();
});
};
在我看来:
<h3 data-bind="text: newInterests().length"></h3>
<div data-bind="foreach: newInterests()">
<p>new interest!</p>
</div>
如果我用数据初始化 newInterests() 数组,它会显示在 DOM 中。如果我调试,我会看到来自服务器的数据被添加到数组中,但由于某种原因视图的绑定没有被更新。知道发生了什么吗?