forked from ember-cli/core-object
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core-object.js
99 lines (79 loc) · 2.66 KB
/
core-object.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
'use strict';
var assignProperties = require('./lib/assign-properties');
var deprecation = require('./lib/deprecation');
function needsNew() {
throw new TypeError("Failed to construct: Please use the 'new' operator, this object constructor cannot be called as a function.");
}
function CoreObject(options) {
if (!(this instanceof CoreObject)) {
needsNew()
}
this.init(options);
}
CoreObject.prototype.init = function(options) {
if (options) {
for (var key in options) {
this[key] = options[key];
}
}
};
CoreObject.extend = function(options) {
var constructor = this;
function Class() {
var length = arguments.length;
if (length === 0) this.init();
else if (length === 1) this.init(arguments[0]);
else this.init.apply(this, arguments);
}
Class.__proto__ = CoreObject;
Class.prototype = Object.create(constructor.prototype);
if (options) {
if (shouldCallSuper(options.init)) {
if (hasArgs(options.init)) {
deprecation(
'Overriding init without calling this._super is deprecated. ' +
'Please call this._super(), addon: `' + options.name + '`'
);
options.init = forceSuperWithoutApply(options.init);
} else {
// this._super.init && is to make sure that the deprecation message
// works for people who are writing addons supporting before 2.6.
deprecation(
'Overriding init without calling this._super is deprecated. ' +
'Please call `this._super.init && this._super.init.apply(this, arguments);` addon: `' + options.name + '`'
);
options.init = forceSuper(options.init);
}
}
assignProperties(Class.prototype, options);
}
return Class;
};
function hasArgs(fn) {
// Takes arguments, assume disruptive override
return /^function *\( *[^ )]/.test(fn);
}
/* global define:true module:true window: true */
if (typeof define === 'function' && define['amd']) { define(function() { return CoreObject; }); }
if (typeof module !== 'undefined' && module['exports']) { module['exports'] = CoreObject; }
if (typeof window !== 'undefined') { window['CoreObject'] = CoreObject; }
function shouldCallSuper(fn) {
// No function, no problem
if (!fn) { return false; }
// Calls super already, good to go
if (/this\._super\(/.test(fn)) { return false; }
if (/this\._super\./.test(fn)) { return false; }
return true;
}
function forceSuper(fn) {
return function() {
this._super.apply(this, arguments);
fn.apply(this, arguments);
}
}
function forceSuperWithoutApply(fn) {
return function() {
this._super.call(this);
fn.apply(this, arguments);
}
}