Repository navigation
Expand file tree
/
Copy path5 - General pattern for wrapping a web service.js
More file actions
81 lines (77 loc) · 2.54 KB
/
Copy path5 - General pattern for wrapping a web service.js
File metadata and controls
81 lines (77 loc) · 2.54 KB
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
/* WebserviceProxy class */
// 从上一个例子中提炼出一个更加通用的Web服务包装模式。
// 不是一个单例,而是一个拥有构造函数的普通类,以便以后进行扩展。
var WebserviceProxy = function() {
this.xhrHandler = XhrManager.createXhrHandler();
};
WebserviceProxy.prototype = {
// 请求错误的处理函数
_xhrFailure: function(statusCode) {
throw new Error('StatsProxy: Asynchronous request for stats failed.');
},
// 发送请求的函数
_fetchData: function(url, dataCallback, getVars) {
var that = this;
var callback = {
success: function(responseText) {
var obj = eval('(' + responseText + ')');
dataCallback(obj);
},
failure: that._xhrFailure
};
var getVarArray = [];
for(varName in getVars) {
getVarArray.push(varName + '=' + getVars[varName]);
}
if(getVarArray.length > 0) {
url = url + '?' + getVarArray.join('&');
}
xhrHandler.request('GET', url, callback);
}
};
// 使用这个通用模式时,只需从WebserviceProxy派生一个子类,然后再借助_fetchData方法实现需要的方法即可
// 如果把StatsProxy类实现为WebserviceProxy的子类,其结果大致如下:
/* StatsProxy class, using WebserviceProxy. */
var StatsProxy = function() {}; // implements PageStats
extend(StatsProxy, WebserviceProxy);
/* Implement the needed methods. */
// 借助_fetchData方法实现需要的方法
StatsProxy.prototype.getPageviews = function(callback, startDate, endDate,
page) {
this._fetchData('/stats/getPageviews/', callback, {
'startDate': startDate,
'endDate': endDate,
'page': page
});
};
StatsProxy.prototype.getUniques = function(callback, startDate, endDate,
page) {
this._fetchData('/stats/getUniques/', callback, {
'startDate': startDate,
'endDate': endDate,
'page': page
});
};
StatsProxy.prototype.getBrowserShare = function(callback, startDate, endDate,
page) {
this._fetchData('/stats/getBrowserShare/', callback, {
'startDate': startDate,
'endDate': endDate,
'page': page
});
};
StatsProxy.prototype.getTopSearchTerms = function(callback, startDate,
endDate, page) {
this._fetchData('/stats/getTopSearchTerms/', callback, {
'startDate': startDate,
'endDate': endDate,
'page': page
});
};
StatsProxy.prototype.getMostVisitedPages = function(callback, startDate,
endDate) {
this._fetchData('/stats/getMostVisitedPages/', callback, {
'startDate': startDate,
'endDate': endDate
});
};