forked from aralejs/autocomplete
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata-source.js
More file actions
120 lines (101 loc) · 2.72 KB
/
Copy pathdata-source.js
File metadata and controls
120 lines (101 loc) · 2.72 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
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
var Base = require('arale-base');
var $ = require('jquery');
var DataSource = Base.extend({
attrs: {
source: null,
type: 'array'
},
initialize: function (config) {
DataSource.superclass.initialize.call(this, config);
// 每次发送请求会将 id 记录到 callbacks 中,返回后会从中删除
// 如果 abort 会清空 callbacks,之前的请求结果都不会执行
this.id = 0;
this.callbacks = [];
var source = this.get('source');
if (isString(source)) {
this.set('type', 'url');
} else if ($.isArray(source)) {
this.set('type', 'array');
} else if ($.isPlainObject(source)) {
this.set('type', 'object');
} else if ($.isFunction(source)) {
this.set('type', 'function');
} else {
throw new Error('Source Type Error');
}
},
getData: function (query) {
return this['_get' + capitalize(this.get('type') || '') + 'Data'](query);
},
abort: function () {
this.callbacks = [];
},
// 完成数据请求,getData => done
_done: function (data) {
this.trigger('data', data);
},
_getUrlData: function (query) {
var that = this,
options;
var obj = {
query: query ? encodeURIComponent(query) : '',
timestamp: new Date().getTime()
};
var url = this.get('source').replace(/\{\{(.*?)\}\}/g, function (all, match) {
return obj[match];
});
var callbackId = 'callback_' + this.id++;
this.callbacks.push(callbackId);
if (/^(https?:\/\/)/.test(url)) {
options = {
dataType: 'jsonp'
};
} else {
options = {
dataType: 'json'
};
}
$.ajax(url, options).success(function (data) {
if ($.inArray(callbackId, that.callbacks) > -1) {
delete that.callbacks[callbackId];
that._done(data);
}
}).error(function () {
if ($.inArray(callbackId, that.callbacks) > -1) {
delete that.callbacks[callbackId];
that._done({});
}
});
},
_getArrayData: function () {
var source = this.get('source');
this._done(source);
return source;
},
_getObjectData: function () {
var source = this.get('source');
this._done(source);
return source;
},
_getFunctionData: function (query) {
var that = this,
func = this.get('source');
// 如果返回 false 可阻止执行
var data = func.call(this, query, done);
if (data) {
this._done(data);
}
function done(data) {
that._done(data);
}
}
});
module.exports = DataSource;
function isString(str) {
return Object.prototype.toString.call(str) === '[object String]';
}
function capitalize(str) {
return str.replace(/^([a-z])/, function (f, m) {
return m.toUpperCase();
});
}