forked from Jemt/Fit.UI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCore.js
371 lines (328 loc) · 12.5 KB
/
Core.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
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
/// <container name="Fit.Core">
/// Core features extending the capabilities of native JS
/// </container>
Fit = {};
Fit.Core = {};
/// <function container="Fit.Core" name="Extend" access="public" static="true">
/// <description>
/// Extend any object with the public members of a super class.
///
/// MyClass = function(controlId)
/// {
///      Fit.Core.Extend(this, MySuperClass).Apply();
/// }
///
/// The code above defines a class called MyClass which extends from MySuperClass.
/// Use Apply() to pass variables to the super class constructor as shown below:
///
/// Male = function(name, age)
/// {
///      Fit.Core.Extend(this, Person).Apply("Male", name, age);
/// }
///
/// Notice that calling just Extend(..) without calling Apply() on the object returned,
/// will not cause extension to occure. Apply() must be called, with or without parameters.
/// </description>
/// <param name="subInstance" type="object"> Instance of sub class to extend </param>
/// <param name="superType" type="function"> Class (function) to extend from </param>
/// </function>
Fit.Core.Extend = function(subInstance, superType)
{
Fit.Validation.ExpectIsSet(subInstance);
Fit.Validation.ExpectFunction(superType);
var binder =
{
Apply: function()
{
superType.apply(subInstance, arguments);
// Support for Fit.Core.Extends(..)
if (!subInstance._internal)
subInstance._internal = {};
if (!subInstance._internal.Extends)
subInstance._internal.Extends = [];
Fit.Array.Add(subInstance._internal.Extends, superType);
}
}
return binder;
}
/// <function container="Fit.Core" name="Extends" access="public" static="true" returns="boolean">
/// <description>
/// Returns boolean indicating whether given object is an extension of a given super type - see Fit.Core.Extend(..).
/// Also look into Fit.Core.InstanceOf(..) which may provide the desired behaviour.
/// </description>
/// <param name="instance" type="object"> Object instance </param>
/// <param name="superType" type="function"> Reference to super class (function) </param>
/// </function>
Fit.Core.Extends = function(instance, superType)
{
Fit.Validation.ExpectIsSet(instance);
Fit.Validation.ExpectFunction(superType);
return (instance._internal && instance._internal.Extends && Fit.Array.Contains(instance._internal.Extends, superType) === true);
}
/// <function container="Fit.Core" name="InstanceOf" access="public" static="true" returns="boolean">
/// <description>
/// Returns boolean indicating whether given object is an instance or extension of a given class type - see Fit.Core.Extend(..).
/// This is equivalent of: var result = (obj instanceof MyType || Fit.Core.Extends(obj, MyType));
/// </description>
/// <param name="instance" type="object"> Object instance </param>
/// <param name="type" type="function"> Reference to class (function) </param>
/// </function>
Fit.Core.InstanceOf = function(instance, type)
{
return (instance instanceof type || Fit.Core.Extends(instance, type) === true);
}
/// <function container="Fit.Core" name="CreateOverride" access="public" static="true" returns="function">
/// <description>
/// Create a function override for any given function using the approach below.
///
/// this.SayHello = function(name) { alert("Hello " + name); }
/// this.SayHello = Fit.Core.CreateOverride(this.SayHello, function(name)
/// {
/// console.log(name + " logged in");
/// console.log(name + " is using the following browser: " + navigator.userAgent);
///
/// base(name); // Call original SayHello function
/// });
///
/// Notice how base(..) allows us to call the original function.
/// </description>
/// <param name="originalFunction" type="function"> Reference to function to override </param>
/// <param name="newFunction" type="function"> Reference to replacement function </param>
/// </function>
Fit.Core.CreateOverride = function(originalFunction, newFunction)
{
Fit.Validation.ExpectFunction(originalFunction);
Fit.Validation.ExpectFunction(newFunction);
return function()
{
var orgBase = window.base; // May already exist
window.base = originalFunction; // Globally accessible base function
var error = null;
var result = undefined;
try // Make sure we can clean up globally accessible base function in case of errors
{
result = newFunction.apply(this, arguments);
}
catch (err)
{
error = err;
}
if (orgBase)
{
window.base = orgBase;
}
else
{
try
{
delete window.base; // Fails in IE8 with "Object doesn't support this action"
}
catch (err)
{
window.base = undefined;
}
}
if (error !== null)
Fit.Validation.ThrowError(error);
if (result !== undefined)
return result;
}
}
/// <function container="Fit.Core" name="IsEqual" access="public" static="true" returns="boolean">
/// <description>
/// Compare two JavaScript objects to determine whether they are identical.
/// Returns True if objects are identical (equal), otherwise False.
/// Functions are compared by reference, not by value.
/// Custom properties set on native JS objects (e.g. Array.XYZ) are not compared, only
/// values are. Naturally JSON objects will be fully compared, including all properties.
/// Be aware of self referencing variables and circular structures, which
/// will cause an infinite loop, and eventually a stack overflow exception.
/// DOM objects and window/frame instances are not supported.
/// </description>
/// <param name="jsObj1" type="object"> JS object to compare agains second JS object </param>
/// <param name="jsObj2" type="object"> JS object to compare agains first JS object </param>
/// </function>
Fit.Core.IsEqual = function(jsObj1, jsObj2)
{
// TEST CASE: Example below is supposed to return: TRUE!
/*var f1 = function() { alert("Hello"); }
var f2 = f1;
Fit.Core.IsEqual(
{
str: "Hello world",
num: 123,
dec: 123.321,
date: new Date("2014-12-01 13:02:23"),
bool: true,
bool2: false,
arr: [100, 200, 250, 400],
arr2: ["Hello", "world"],
arr3: [123, "hello", true, false, new Date("1990-01-20"), [1,2,3], { x: { "hapsen": f1, "hello": new Array(1,2,3) } }],
obj: { a: 123, b: 123.321, c: true, d: false, e: new Date("1993-06-25"), f: "hello", g: null, h: undefined }
},
{
str: "Hello world",
num: 123,
dec: 123.321,
date: new Date("2014-12-01 13:02:23"),
bool: true,
bool2: false,
arr: [100, 200, 250, 400],
arr2: ["Hello", "world"],
arr3: [123, "hello", true, false, new Date("1990-01-20"), [1,2,3], { x: { "hapsen": f2, "hello": new Array(1,2,3) } }],
obj: { a: 123, b: 123.321, c: true, d: false, e: new Date("1993-06-25"), f: "hello", g: null, h: undefined }
});*/
if (typeof(jsObj1) !== typeof(jsObj2))
return false;
if ((jsObj1 === undefined && jsObj2 === undefined) || (jsObj1 === null && jsObj2 === null))
{
return true;
}
else if (typeof(jsObj1) === "string" || typeof(jsObj1) === "boolean")
{
return (jsObj1 === jsObj2);
}
else if (typeof(jsObj1) === "number")
{
if (isNaN(jsObj1) === true && isNaN(jsObj2) === true) // NaN variables are not comparable!
return true;
else
return (jsObj1 === jsObj2);
}
else if (jsObj1 instanceof Date && jsObj2 instanceof Date)
{
return (jsObj1.getTime() === jsObj2.getTime());
}
else if (jsObj1 instanceof Array && jsObj2 instanceof Array)
{
if (jsObj1.length !== jsObj2.length)
return false;
for (var i = 0 ; i < jsObj1.length ; i++)
{
if (Fit.Core.IsEqual(jsObj1[i], jsObj2[i]) === false)
return false;
}
return true;
}
else if (typeof(jsObj1) === "object" && typeof(jsObj2) === "object" && jsObj1 !== null && jsObj2 !== null) // typeof(null) returns "object"
{
for (var k in jsObj1)
if (Fit.Core.IsEqual(jsObj1[k], jsObj2[k]) === false)
return false;
return true;
}
else if (typeof(jsObj1) === "function" && typeof(jsObj2) === "function")
{
// Returns True in the following situation:
// var f1 = function() { alert("Hello"); }
// var f2 = f1;
// Fit.Core.IsEqual(f1, f2);
// Returns False in the following situation:
// var f1 = function() { alert("Hello"); }
// var f2 = function() { alert("Hello"); }
// Fit.Core.IsEqual(f1, f2);
return (jsObj1 === jsObj2);
}
return false;
}
/// <function container="Fit.Core" name="Clone" access="public" static="true" returns="object">
/// <description>
/// Clone JavaScript object. Supported object types and values:
/// String, Number, Boolean, Date, Array, (JSON) Object, Function, Undefined, Null, NaN.
/// Variables defined as undefined are left out of clone,
/// since an undefined variable is equal to a variable defined as undefined.
/// Notice that Arrays and Objects can contain supported object types and values only.
/// Functions are considered references, and as such the cloned object will reference
/// the same functions.
/// Custom properties set on native JS objects (e.g. Array.XYZ) are not cloned, only
/// values are. Naturally custom (JSON) objects will be fully cloned, including all
/// properties. Both arrays and custom (JSON) objects are cloned recursively.
/// Be aware of self referencing variables and circular structures, which
/// will cause an infinite loop, and eventually a stack overflow exception.
/// DOM objects and window/frame instances are not supported.
/// </description>
/// <param name="obj" type="object"> JS object to clone </param>
/// </function>
Fit.Core.Clone = function(obj)
{
// TODO - Known problem:
// var a = new SomeClass();
// var b = (a instanceOf SomeClass);
// var c = (SMCore.Clone(a) instanceOf SomeClass);
// Variable b is True as expected, while variable c is False!
// TODO: Restore/preserve support for instanceof!
// TEST CASE: Example below is supposed to return: TRUE!
/*var f1 = function() { alert("Hello"); }
var x =
{
str: "Hello world",
num: 123,
dec: 123.321,
date: new Date("2014-12-01 13:02:23"),
bool: true,
bool2: false,
arr: [100, 200, 250, 400],
arr2: ["Hello", "world"],
arr3: [123, "hello", true, false, new Date("1990-01-20"), [1,2,3], { x: { "hapsen": f1, "hello": new Array(1,2,3) } }],
obj: { a: 123, b: 123.321, c: true, d: false, e: new Date("1993-06-25"), f: "hello", g: null, h: undefined }
};
var y = SMCore.Clone(x);
console.log("Is equal: " + SMCore.IsEqual(x, y));*/
// Clone object by serializing it into a JSON string, and parse it back into a JS object
var serialized = JSON.stringify(obj); // Returns undefined if obj is either undefined or a function (these are not serialized)
var clone = ((serialized !== undefined) ? JSON.parse(serialized) : serialized); // parse(..) throws error if argument is undefined
// Fixes
// - Dates are serialized into strings - turn back into Date instances.
// - Functions are not serialized (discarded) - add function reference to clone
// - Number variables with a value of NaN is serialized into Null - convert to NaN
var fixClone = null;
fixClone = function(org, clo)
{
if (org instanceof Date) // Dates are turned into string representations - turn back into Date instances
{
return new Date(org.getTime());
}
else if (typeof(org) === "function") // Functions are not serialized - use same reference as original object
{
return org;
}
else if (typeof(org) === "number" && isNaN(org) === true) // NaN is turned into Null - turn back into NaN
{
return parseInt("");
}
else if (org && typeof(org) === "object") // Recursively fix children (object/array)
{
for (var p in org)
clo[p] = fixClone(org[p], clo[p]);
}
return clo;
};
clone = fixClone(obj, clone);
// Done, clone is now identical to original object - SMCore.IsEqual(obj, clone) should return True
return clone;
}
// INTERNAL
Fit._internal = {};
(function()
{
// Find Base URL - e.g. http://server.com/libs/fitui
var src = document.scripts[document.scripts.length - 1].src;
Fit._internal.BaseUrl = src.substring(0, src.lastIndexOf("/"));
// Calculate Base Path - e.g. /libs/fitui
var path = Fit._internal.BaseUrl.replace("http://", "").replace("https://", "");
Fit._internal.BasePath = path.substring(path.indexOf("/"));
})();
/// <function container="Fit" name="GetUrl" access="public" static="true" returns="string">
/// <description> Get fully qualified URL to Fit.UI on server - e.g. http://server.com/libs/fitui </description>
/// </function>
Fit.GetUrl = function()
{
return Fit._internal.BaseUrl;
}
/// <function container="Fit" name="GetPath" access="public" static="true" returns="string">
/// <description> Get absolute path to Fit.UI on server - e.g. /libs/fitui </description>
/// </function>
Fit.GetPath = function()
{
return Fit._internal.BasePath;
}