This repository has been archived by the owner on Dec 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
187 lines (184 loc) · 6.53 KB
/
utils.ts
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
/// <amd-dependency path="jquery"/>
/// <amd-dependency path="jquery.form"/>
import APP = require('khesht/app');
var $:JQueryStatic = require("jquery");
class Utils {
private static strings = {};
private static UID = Date.now();
static isString(value: any): boolean {
return $.type(value) === "string";
}
/*
* returns a unique id
*/
static uniqueId(): string {
return (Utils.UID++).toString(36);
}
static appendString(data): void {
$.extend(this.strings, data);
}
static appendStringPack(name, lang): void {
this.getJSON(['str/', name, '_', lang, '.json'].join(''), null, (json) => {
$.extend(this.strings, json);
this.log('string pack loaded:', name);
}, null, { async: false });
}
static str(key): string {
if (!key)
return null;
var result:any = this.strings;
jQuery(key.split('.')).each(function (index, value) {
if (!result) {
return;
}
result = result[<any>value];
});
return result ? result.trim() : ['[', key, ']'].join('');
}
/*
* it's like JQuery each but also works if given array is null
* you can also bind it simply with adding to parameters
*/
static each(target: any, func: (index: any, value: any) => any, bind?) {
return $.each(target || [], bind ? func.bind(bind) : func);
}
static param(obj:any):string {
return obj ? '?' + $.param(obj) : '';
}
/*
* removes repeated members of given array
*/
static uniqe(array: any[]): any[] {
return array.filter(function (value, index, self) { return self.indexOf(value) === index; });
}
/*
* creates an object with URL parameters values
*/
static parsURL(url:string = location.search): any {
var pairs = url.slice(url.lastIndexOf('?')).replace(/^\?/, '').split(/&/);
var args = {};
this.each(pairs, function (index, pair) {
if ((<string>pair).length > 0) {
pair = pair.split('=');
args[decodeURIComponent(pair[0]).toLowerCase()] = decodeURIComponent(pair[1]);
}
});
return args;
}
static get url(): string {
return [window.location.protocol, '//', window.location.host, location.pathname].join('');
}
/*
* returns clean URL of current location
*/
static baseURL(args: any = null, path: string = '/'): string {
var url = this.url;
return url.slice(0, url.lastIndexOf('/')) + path + this.param(args);
}
static log(...args: any[]) {
args = Array.prototype.slice.call(args);
args.unshift(['<', APP.config.name, '> - '].join(''));
console.log.apply(console, args);
}
static error(data, error) {
console.error.apply(console, [['<', APP.config.name, ' error> - ', error, ':'].join(''), data]);
}
/*
* create an ajax request
* - fails automaticly will handel
*/
static ajax(options: JQueryAjaxSettings = {}): JQueryXHR {
var output = $.ajax(options);
output.fail(this.error.bind(this));
return output;
}
/*
* starts a set of ajax requests and calss success when all of them fetched
* - fails automaticly will handel
* - ajax results automaticly will pass to success
*/
static when(requests: any, success: (results: any) => void, fail?: () => void):void {
var results: { key: string; data: any } = <any>{};
if (requests && Object.keys(requests).length > 0) {
this.each(requests, (key, request: JQueryXHR) => {
request.done((data) => {
data = data && data.error ? null : data;
results[key] = data;
this.log('ajax request recived :', key, '=', data);
}).fail(null);
});
$.when.apply(this, $.map(requests, function (xhr, key) { return xhr; })).then(
() => {
if (success) success(results);
}).fail(
(jqXHR, textStatus) => {
fail ? fail() : this.error(jqXHR, 'ajax set request failed : ' + textStatus);
});
} else {
if (success) success(results);
}
}
/*
* create an ajax JSON request
* - fails automaticly will handel
* - you can send a form jQuery element as data but getJSON will return null instead of JQueryXHR
*/
static getJSON(url: string, data: any = null, success?: (data: any) => void, fail?: (error: string) => void, options: JQueryAjaxSettings = {}): JQueryXHR {
options = $.extend({
dataType: 'json',
url: url,
data: data,
success: (json) => {
var error: any = json ? json.error : null;
if (error) {
if (fail) {
fail(error);
}
this.error(error, 'server error');
} else if (success) {
this.log('server call returned:', json);
success(json);
}
},
error: fail
}, options);
if (data instanceof jQuery) {
delete options.data;
data.prop('tagName') == 'FORM' && data.ajaxSubmit(options);
return null;
} else {
return this.ajax(options);
}
}
static apiURL(call: string, args: any = null): string {
args = args || {};
args.call = call;
return $.param(args);
}
/*
* calls a KAPI api request
* - fails automaticly will handel
*/
static api(call: string, args: any = null, success?: (data: any) => void, fail?: (error: string) => {}, options: JQueryAjaxSettings = {}): JQueryXHR {
args = args || {};
args.call = call;
return this.getJSON(require.toUrl('api/'), args, success, fail, options);
}
/*
* loads a requireJS module
* - fails automaticly will handel
* - paths automaticly match with requireJS configs
*/
static loadModule(modulePath: string, success: (module: any) => void, fail?: () => void) {
require.call(null, [modulePath],
(module) => {
this.log('module file loaded:', modulePath);
success(module);
},
(err) => {
this.error(err.requireModules && err.requireModules[0], 'loading module failed');
if (fail) fail();
});
}
}
export = Utils;