/
ajax.js
113 lines (100 loc) · 2.75 KB
/
ajax.js
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
// v0.2
goog.provide('mvc.sync.Ajax');
goog.require('mvc.sync');
goog.require('goog.net.XhrManager');
/**
* @implements {mvc.sync}
*/
mvc.sync.Ajax = function(url) {
this.baseUrls_ = {};
if(goog.isString(url) || goog.isFunction(url)) {
url = {
create: url,
read: url,
update: url,
del: url,
};
}
goog.object.extend(this.baseUrls_, goog.object.map(url, function(val) {
if(goog.isString(val))
return function(model) {val.replace(/:(\w+)/g, function(id) {
return model.get(id);
});};
return val;
});
this.xhr_ = new goog.net.XhrManager();
this.sendCount_ = 0;
};
/**
* @inheritDoc
*/
mvc.sync.Ajax.prototype.create = function(model, callback) {
this.xhr_.send(this.sendCount_++, this.baseUrls_.create(model),
"POST", model.getJson(), undefined,
goog.bind(this.onCreateComplete, this, model, callback));
};
/**
* @inheritDoc
*/
mvc.sync.Ajax.prototype.read = function(model, callback) {
this.xhr_.send(this.sendCount_++, this.baseUrls_.read(model),
"GET", undefined, undefined,
goog.bind(this.onComplete, this, model, callback));
};
/**
* @inheritDoc
*/
mvc.sync.Ajax.prototype.update = function(model, callback) {
this.xhr_.send(this.sendCount_++, this.baseUrls_.update(model),
"PUT", model.getJson(), undefined,
goog.bind(this.onUpdateComplete, this, model, callback));
};
/**
* @inheritDoc
*/
mvc.sync.Ajax.prototype.delete = function(model, callback) {
this.xhr_.send(this.sendCount_++, this.baseUrls_.del(model),
"DELETE", undefined, undefined,
goog.bind(this.onDeleteComplete, this, model, callback));
};
/**
* override this to do processing on returned data
*
* @param {mvc.Model} model
* @param {Function} callback
* @param {Event} e
*/
mvc.sync.Ajax.prototype.onCreateComplete_ = function(model, callback, e) {
var xhr = e.target;
model.set('id') = xhr.getResponseJson()['result']['id'];
};
/**
* override this to do processing on returned data
*
* @param {mvc.Model} model
* @param {Function} callback
* @param {Event} e
*/
mvc.sync.Ajax.prototype.onReadComplete_ = function(model, callback, e) {
var xhr = e.target;
var json = xhr.getResponseJson()['result'];
goog.model.set(json);
};
/**
* override this to do processing on returned data
*
* @param {mvc.Model} model
* @param {Function} callback
* @param {Event} e
*/
mvc.sync.Ajax.prototype.onUpdateComplete_ = function(model, callback, e) {
};
/**
* override this to do processing on returned data
*
* @param {mvc.Model} model
* @param {Function} callback
* @param {Event} e
*/
mvc.sync.Ajax.prototype.onDelComplete_ = function(model, callback, e) {
};