1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
|
ko.collectionItem = function(initialData, parentCollection) {
var self = {
isFetched: ko.observable(false)
};
var links = [];
var etag = null;
var url = null;
var attributes = ko.observableArray([]);
var collection = parentCollection;
var dirtyFlag = ko.observable(false);
/* Private methods */
/*
Given the incoming 'data' for this object, look through the fields for
things that differ between the server representation and the client
representation. Store both values for any differences in an attribute
of the observable called conflicts().
For each conflict, create a member function on the observable that
allows you to resolve the conflict. When the last conflict is resolved,
our etag is updated to the value the server gave us.
This method returns true if all conflicts could be resolved (ie, the
data in all fields was the same, just the etag had changed).
*/
var parseConflicts = function(data, newEtag) {
$.each(data, function(attr, value){
if (attr !== "links") {
if ($.compare(value, self[attr]() === undefined ? "" : self[attr]())) {
// Server and client values match.
// We need to do some funky stuff with undefined values, and treat
// them as "". I don't really like this, but it works for now.
self[attr].conflicts([]);
self[attr].resolveConflict = function(){};
} else {
self[attr].conflicts([value, self[attr]() === undefined ? "" : self[attr]()]);
self[attr].resolveConflict = function(chosenValue) {
// Mark the entire object as dirty, so we can allow it to be
// saved, even if we set it to the original value we had (which
// differed from the server's value).
self.isDirty(true);
self[attr](chosenValue);
self[attr].conflicts([]);
if (!self.hasConflicts()) {
// If this was the last conflict, we can use the new etag from
// the server.
etag = newEtag;
}
};
}
}
});
var conflicts = self.hasConflicts();
if (!conflicts) {
etag = newEtag;
}
return !conflicts;
};
/*
Given an object containing errors, we want to apply each of these
errors onto the relevant field. We want to remove any errors that are
already on any field.
If we have any errors leftover, we need to notify globally, using the
parentCollection's messages object.
*/
var markErrors = function(errors) {
$.each(attributes(), function(i,attr){
if (!self[attr].errors) {
self[attr].errors = ko.observableArray([]);
}
if (errors[attr]) {
self[attr].errors(errors[attr]);
delete errors[attr];
} else {
self[attr].errors([]);
}
});
$.each(errors, function(field){
parentCollection.messages({type:"error", message: field + ": " + errors[field].join("<br>"), timeout: 3000});
});
};
/*
Get the attributes ready for sending to the server.
We can't just iterate through properties, as some will not apply. We
use the convention that we will only send back properties that the
server sent to us.
*/
var prepareAttributes = function() {
var data = {};
$.each(attributes(), function(i,attr){
data[attr] = self[attr]();
});
return data;
};
/* Public methods */
/*
Update the data fields associated with this object from the provided
data.
This may create new attributes, which need to be noted so we can send
those values back to the server.
We can mark all updated attributes as not dirty, not conflicted, and
not having errors.
*/
self.updateData = function(data) {
if (data.links) {
// We want to store the links, but not attach them to the object.
links = data.links;
delete data.links;
$.each(links, function(i, obj){
if (obj.rel === "self") {
url = obj.uri;
}
});
}
$.each(data, function(attr, value){
if (attributes().indexOf(attr) < 0) {
self[attr] = ko.observable(value);
self[attr].errors = ko.observableArray([]);
self[attr].conflicts = ko.observableArray([]);
ko.dirtyFlag(self[attr], false);
// Need to add this last to cause the dirtyFields dependentObservable
// to work correctly when editing the last field.
attributes.push(attr);
} else {
self[attr](value);
self[attr].errors([]);
self[attr].conflicts([]);
self[attr].isDirty.reset();
}
});
// Put the links back in case a post-processor needs them.
data.links = links;
};
self.serialize = function(evt) {
return JSON.stringify(prepareAttributes());
};
/*
Discard any local changes, and pull the data from the server.
*/
self.revert = function(evt) {
etag = null;
self.fetch();
parentCollection.messages({type:'warning', message:'The object "' + self.name() + '" was reverted to the version stored on the server.', timeout: 5000});
};
/*
Attempt to save the data to the server.
Only permitted to do this if we have successfully fetched the data
at some point.
Notes: We use POST instead of PUT, in case we do not have access to
all of the fields of the object. PUT implies the complete resource
is being updated.
Errors may come back in {'field-errors': []}, or {'detail':[]}.
Currently, this makes assumptions about server type, which are
bad. I need to refactor the error handling code. (400,409)
Precondition Failed (412) needs to be handled differently, as
we need to fetch the data from the server if none was provided
as to the current state of the resource.
*/
self.save = function(evt) {
if (self.isFetched()) {
$.ajax({
url: url,
type: 'post', // We can't PUT in case we don't know about all fields.
headers: {'If-Match': etag},
data: self.serialize(),
statusCode: {
200: function(data, textStatus, jqXHR) {
// Object saved.
// Incase some fields were reformatted by the server, redo our data.
self.updateData(data);
etag = jqXHR.getResponseHeader('Etag');
parentCollection.messages({type:'success', message:'The object "' + self.name() + '" was saved.', timeout: 2500});
self.isDirty(false);
},
201: function(data, textStatus, jqXHR) {
// Object saved for the first time (created)
// Incase some fields were reformatted by the server, redo our data.
self.updateData(data);
etag = jqXHR.getResponseHeader('Etag');
url = jqXHR.getResponseHeader('Location');
parentCollection.messages({type:'success', message:'The object "' + self.name() + '" was created.', timeout: 2500});
self.isDirty(false);
},
400: function(jqXHR, textStatus, errorThrown) {
var data = JSON.parse(jqXHR.responseText);
if (data['field-errors']) {
markErrors(data['field-errors']);
}
parentCollection.messages({type:'error', message:'The object "' + self.name() + '" could not be saved. Please check the highlighted field(s).', timeout: 10000});
},
409: function(jqXHR, textStatus, errorThrown) {
// Errors saving the data. Likely to be validation errors.
// We should have a detail object with info to display.
var data = JSON.parse(jqXHR.responseText);
if (data.detail) {
markErrors(data.detail);
}
parentCollection.messages({type:'error', message:'The object "' + self.name() + '" could not be saved. Please check the highlighted field(s).', timeout: 10000});
},
412: function(jqXHR, textStatus, errorThrown) {
// Data was changed on server since we last fetched it.
// There may be conflicts to deal with.
// See if the server gave us a current version back...
var data, serverEtag;
if (jqXHR.responseText) {
data = JSON.parse(jqXHR.responseText);
} else {
$.ajax({
url: url,
async: false,
success: function(newData, textStatus, jqXHR) {
data = newData;
serverEtag = jqXHR.getResponseHeader('Etag');
}
});
}
if (parseConflicts(data, serverEtag)) {
// We were able to resolve all of the conflicts, now we can
// try to re-save; but only if it was the first time we saved,
// to prevent inifinite recursion.
if (evt) {
self.save();
}
} else {
parentCollection.messages({type:'error', message:'The object "' + self.name() + '" has been modified on the server. Please check the changed field(s) and select the appropriate value(s).', timeout: 10000});
}
}
}
});
}
};
/*
Permanently delete the object from the server.
*/
self.destroy = function(evt) {
if (self.isFetched() && etag) {
console.log("DELETING ITEM");
$.ajax({
url: url,
type: 'delete',
headers: {'If-Match': etag},
success: function(data, textStatus, jqXHR) {
if (collection) {
collection.items.remove(self);
}
parentCollection.messages({type:'success', message:'The object "' + self.name() + '" was deleted.', timeout: 2500});
},
error: function(jqXHR, textStatus, errorThrown) {
// Display error message about not being able to delete?
parentCollection.messages({type:'error', message:'The object "' + self.name() + '" could not be deleted.', timeout: 10000});
}
});
}
};
/*
(Re)Fetch the resource from the server.
Handle conflicts if the arise (when the object has already been fetchd)
*/
self.fetch = function(evt) {
var headers = {};
if (etag) {
headers['If-None-Match'] = etag;
}
$.ajax({
type: 'get',
url: url,
headers: headers,
statusCode: {
200: function(data, textStatus, jqXHR) {
// If we have an etag already, this means the object has been
// updated on the server, and we need to look for conflicts.
if (etag) {
var serverEtag = jqXHR.getResponseHeader('Etag');
// If we were unable to handle all conflicts, we need to exit.
if (!parseConflicts(data, serverEtag)) {
parentCollection.messages({type:'error', message:'The object "' + self.name() + '" has been modified on the server. Please check the changed field(s) and select the appropriate value(s).', timeout: 10000});
return;
};
}
// Otherwise, we can update the data and the etag.
self.updateData(data);
etag = jqXHR.getResponseHeader('Etag');
self.isFetched(true);
},
304: function() {
}
},
error: function(jqXHR, textStatus, errorThrown) {
parentCollection.messages({type:"error", message:"There was an error fetching the data from the server"});
}
});
};
/* Dependent Observables */
self.dirtyFields = ko.dependentObservable(function(){
return ko.utils.arrayFilter(attributes(), function(attr){
return self[attr] && self[attr].isDirty && self[attr].isDirty();
});
});
self.conflictedFields = ko.dependentObservable(function() {
return ko.utils.arrayFilter(attributes(), function(attr){
return self[attr] && self[attr].conflicts && self[attr].conflicts().length > 0;
});
});
var filterAttributes = function(property) {
return function() {
return ko.utils.arrayFilter(attributes(), function(attr){
return self[attr] && self[attr][property] && self[attr][property]().length > 0;
}).length > 0;
};
};
self.hasErrors = ko.dependentObservable(filterAttributes('errors'));
self.hasConflicts = ko.dependentObservable(filterAttributes('conflicts'));
/*
An object is dirty when:
- any of its fields/attributes are dirty. (we aks them), OR
- we have explicitly marked it as dirty.
We need to do the latter for when we have merged a conflict, by choosing
our value, which differed from the server. The local model would
normally think it wasn't dirty, but it differs from the server, and
does need to be saved.
*/
self.isDirty = ko.dependentObservable({
read: function() {
return self.dirtyFields().length > 0 || dirtyFlag();
},
write: function(value) {
dirtyFlag(value);
if (!value) {
$.each(attributes(), function(attr){
if (self[attr] && self[attr].isDirty) {
console.log(attr);
self[attr].isDirty.reset();
}
});
}
}
});
/*
Can this object be saved back to the server?
Only when it is dirty, and has been fetched.
*/
self.canSave = ko.dependentObservable(function() {
return self.isDirty() && self.isFetched();
});
self._etag = function(){return etag;};
self._attributes = function(){ return attributes();};
self._url = function() {return url;};
if (initialData) {
self.updateData(initialData);
}
return self;
};
|