问题
I have Durandal viewmodel working like so:
define(function (require) {
var http = require('durandal/http');
return {
subjectItem: function (data) {
var self = this;
self.Subject_ID = data.Subject_ID;
self.Subject_Name = data.Subject_Name;
},
subjects: ko.observableArray([]),
activate: function () {
var self = this;
http.ajaxRequest("get", "/api/values/getsubjects")
.done(function (allData) {
var mappedSubjects = $.map(allData, function (list) { return new self.subjectItem(list); });
self.subjects(mappedSubjects);
});
}
};
});
However, on first navigating to this view it runs the ajax call but does not change the dom, navigate to it again and they all appear (still runs ajax call). This is my html:
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody data-bind="foreach: subjects">
<tr>
<td data-bind="text: Subject_Name"></td>
</tr>
</tbody>
</table>
Any clues, I'm very new to using Durandal but now worried it won't effectively keep the dom updated.
回答1:
I think your problem is very similar to: HotTowel: Viewmodel lose mapping when navigating between pages
An AJAX call is an asyncronous task so you need to return a promise in the activate function for tell to durandal to wait until the data is retrieved before to proceed to apply bindings.
来源:https://stackoverflow.com/questions/15415436/durandal-ko-binding-view-issue