Aucune description

index.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. 'use strict';
  2. var util = require('util');
  3. var define = require('define-property');
  4. var CacheBase = require('cache-base');
  5. var Emitter = require('component-emitter');
  6. var isObject = require('isobject');
  7. var merge = require('mixin-deep');
  8. var pascal = require('pascalcase');
  9. var cu = require('class-utils');
  10. /**
  11. * Optionally define a custom `cache` namespace to use.
  12. */
  13. function namespace(name) {
  14. var Cache = name ? CacheBase.namespace(name) : CacheBase;
  15. var fns = [];
  16. /**
  17. * Create an instance of `Base` with the given `config` and `options`.
  18. *
  19. * ```js
  20. * // initialize with `config` and `options`
  21. * var app = new Base({isApp: true}, {abc: true});
  22. * app.set('foo', 'bar');
  23. *
  24. * // values defined with the given `config` object will be on the root of the instance
  25. * console.log(app.baz); //=> undefined
  26. * console.log(app.foo); //=> 'bar'
  27. * // or use `.get`
  28. * console.log(app.get('isApp')); //=> true
  29. * console.log(app.get('foo')); //=> 'bar'
  30. *
  31. * // values defined with the given `options` object will be on `app.options
  32. * console.log(app.options.abc); //=> true
  33. * ```
  34. *
  35. * @param {Object} `config` If supplied, this object is passed to [cache-base][] to merge onto the the instance upon instantiation.
  36. * @param {Object} `options` If supplied, this object is used to initialize the `base.options` object.
  37. * @api public
  38. */
  39. function Base(config, options) {
  40. if (!(this instanceof Base)) {
  41. return new Base(config, options);
  42. }
  43. Cache.call(this, config);
  44. this.is('base');
  45. this.initBase(config, options);
  46. }
  47. /**
  48. * Inherit cache-base
  49. */
  50. util.inherits(Base, Cache);
  51. /**
  52. * Add static emitter methods
  53. */
  54. Emitter(Base);
  55. /**
  56. * Initialize `Base` defaults with the given `config` object
  57. */
  58. Base.prototype.initBase = function(config, options) {
  59. this.options = merge({}, this.options, options);
  60. this.cache = this.cache || {};
  61. this.define('registered', {});
  62. if (name) this[name] = {};
  63. // make `app._callbacks` non-enumerable
  64. this.define('_callbacks', this._callbacks);
  65. if (isObject(config)) {
  66. this.visit('set', config);
  67. }
  68. Base.run(this, 'use', fns);
  69. };
  70. /**
  71. * Set the given `name` on `app._name` and `app.is*` properties. Used for doing
  72. * lookups in plugins.
  73. *
  74. * ```js
  75. * app.is('foo');
  76. * console.log(app._name);
  77. * //=> 'foo'
  78. * console.log(app.isFoo);
  79. * //=> true
  80. * app.is('bar');
  81. * console.log(app.isFoo);
  82. * //=> true
  83. * console.log(app.isBar);
  84. * //=> true
  85. * console.log(app._name);
  86. * //=> 'bar'
  87. * ```
  88. * @name .is
  89. * @param {String} `name`
  90. * @return {Boolean}
  91. * @api public
  92. */
  93. Base.prototype.is = function(name) {
  94. if (typeof name !== 'string') {
  95. throw new TypeError('expected name to be a string');
  96. }
  97. this.define('is' + pascal(name), true);
  98. this.define('_name', name);
  99. this.define('_appname', name);
  100. return this;
  101. };
  102. /**
  103. * Returns true if a plugin has already been registered on an instance.
  104. *
  105. * Plugin implementors are encouraged to use this first thing in a plugin
  106. * to prevent the plugin from being called more than once on the same
  107. * instance.
  108. *
  109. * ```js
  110. * var base = new Base();
  111. * base.use(function(app) {
  112. * if (app.isRegistered('myPlugin')) return;
  113. * // do stuff to `app`
  114. * });
  115. *
  116. * // to also record the plugin as being registered
  117. * base.use(function(app) {
  118. * if (app.isRegistered('myPlugin', true)) return;
  119. * // do stuff to `app`
  120. * });
  121. * ```
  122. * @name .isRegistered
  123. * @emits `plugin` Emits the name of the plugin being registered. Useful for unit tests, to ensure plugins are only registered once.
  124. * @param {String} `name` The plugin name.
  125. * @param {Boolean} `register` If the plugin if not already registered, to record it as being registered pass `true` as the second argument.
  126. * @return {Boolean} Returns true if a plugin is already registered.
  127. * @api public
  128. */
  129. Base.prototype.isRegistered = function(name, register) {
  130. if (this.registered.hasOwnProperty(name)) {
  131. return true;
  132. }
  133. if (register !== false) {
  134. this.registered[name] = true;
  135. this.emit('plugin', name);
  136. }
  137. return false;
  138. };
  139. /**
  140. * Define a plugin function to be called immediately upon init. Plugins are chainable
  141. * and expose the following arguments to the plugin function:
  142. *
  143. * - `app`: the current instance of `Base`
  144. * - `base`: the [first ancestor instance](#base) of `Base`
  145. *
  146. * ```js
  147. * var app = new Base()
  148. * .use(foo)
  149. * .use(bar)
  150. * .use(baz)
  151. * ```
  152. * @name .use
  153. * @param {Function} `fn` plugin function to call
  154. * @return {Object} Returns the item instance for chaining.
  155. * @api public
  156. */
  157. Base.prototype.use = function(fn) {
  158. fn.call(this, this);
  159. return this;
  160. };
  161. /**
  162. * The `.define` method is used for adding non-enumerable property on the instance.
  163. * Dot-notation is **not supported** with `define`.
  164. *
  165. * ```js
  166. * // arbitrary `render` function using lodash `template`
  167. * app.define('render', function(str, locals) {
  168. * return _.template(str)(locals);
  169. * });
  170. * ```
  171. * @name .define
  172. * @param {String} `key` The name of the property to define.
  173. * @param {any} `value`
  174. * @return {Object} Returns the instance for chaining.
  175. * @api public
  176. */
  177. Base.prototype.define = function(key, val) {
  178. if (isObject(key)) {
  179. return this.visit('define', key);
  180. }
  181. define(this, key, val);
  182. return this;
  183. };
  184. /**
  185. * Mix property `key` onto the Base prototype. If base is inherited using
  186. * `Base.extend` this method will be overridden by a new `mixin` method that will
  187. * only add properties to the prototype of the inheriting application.
  188. *
  189. * ```js
  190. * app.mixin('foo', function() {
  191. * // do stuff
  192. * });
  193. * ```
  194. * @name .mixin
  195. * @param {String} `key`
  196. * @param {Object|Array} `val`
  197. * @return {Object} Returns the `base` instance for chaining.
  198. * @api public
  199. */
  200. Base.prototype.mixin = function(key, val) {
  201. Base.prototype[key] = val;
  202. return this;
  203. };
  204. /**
  205. * Non-enumberable mixin array, used by the static [Base.mixin]() method.
  206. */
  207. Base.prototype.mixins = Base.prototype.mixins || [];
  208. /**
  209. * Getter/setter used when creating nested instances of `Base`, for storing a reference
  210. * to the first ancestor instance. This works by setting an instance of `Base` on the `parent`
  211. * property of a "child" instance. The `base` property defaults to the current instance if
  212. * no `parent` property is defined.
  213. *
  214. * ```js
  215. * // create an instance of `Base`, this is our first ("base") instance
  216. * var first = new Base();
  217. * first.foo = 'bar'; // arbitrary property, to make it easier to see what's happening later
  218. *
  219. * // create another instance
  220. * var second = new Base();
  221. * // create a reference to the first instance (`first`)
  222. * second.parent = first;
  223. *
  224. * // create another instance
  225. * var third = new Base();
  226. * // create a reference to the previous instance (`second`)
  227. * // repeat this pattern every time a "child" instance is created
  228. * third.parent = second;
  229. *
  230. * // we can always access the first instance using the `base` property
  231. * console.log(first.base.foo);
  232. * //=> 'bar'
  233. * console.log(second.base.foo);
  234. * //=> 'bar'
  235. * console.log(third.base.foo);
  236. * //=> 'bar'
  237. * // and now you know how to get to third base ;)
  238. * ```
  239. * @name .base
  240. * @api public
  241. */
  242. Object.defineProperty(Base.prototype, 'base', {
  243. configurable: true,
  244. get: function() {
  245. return this.parent ? this.parent.base : this;
  246. }
  247. });
  248. /**
  249. * Static method for adding global plugin functions that will
  250. * be added to an instance when created.
  251. *
  252. * ```js
  253. * Base.use(function(app) {
  254. * app.foo = 'bar';
  255. * });
  256. * var app = new Base();
  257. * console.log(app.foo);
  258. * //=> 'bar'
  259. * ```
  260. * @name #use
  261. * @param {Function} `fn` Plugin function to use on each instance.
  262. * @return {Object} Returns the `Base` constructor for chaining
  263. * @api public
  264. */
  265. define(Base, 'use', function(fn) {
  266. fns.push(fn);
  267. return Base;
  268. });
  269. /**
  270. * Run an array of functions by passing each function
  271. * to a method on the given object specified by the given property.
  272. *
  273. * @param {Object} `obj` Object containing method to use.
  274. * @param {String} `prop` Name of the method on the object to use.
  275. * @param {Array} `arr` Array of functions to pass to the method.
  276. */
  277. define(Base, 'run', function(obj, prop, arr) {
  278. var len = arr.length, i = 0;
  279. while (len--) {
  280. obj[prop](arr[i++]);
  281. }
  282. return Base;
  283. });
  284. /**
  285. * Static method for inheriting the prototype and static methods of the `Base` class.
  286. * This method greatly simplifies the process of creating inheritance-based applications.
  287. * See [static-extend][] for more details.
  288. *
  289. * ```js
  290. * var extend = cu.extend(Parent);
  291. * Parent.extend(Child);
  292. *
  293. * // optional methods
  294. * Parent.extend(Child, {
  295. * foo: function() {},
  296. * bar: function() {}
  297. * });
  298. * ```
  299. * @name #extend
  300. * @param {Function} `Ctor` constructor to extend
  301. * @param {Object} `methods` Optional prototype properties to mix in.
  302. * @return {Object} Returns the `Base` constructor for chaining
  303. * @api public
  304. */
  305. define(Base, 'extend', cu.extend(Base, function(Ctor, Parent) {
  306. Ctor.prototype.mixins = Ctor.prototype.mixins || [];
  307. define(Ctor, 'mixin', function(fn) {
  308. var mixin = fn(Ctor.prototype, Ctor);
  309. if (typeof mixin === 'function') {
  310. Ctor.prototype.mixins.push(mixin);
  311. }
  312. return Ctor;
  313. });
  314. define(Ctor, 'mixins', function(Child) {
  315. Base.run(Child, 'mixin', Ctor.prototype.mixins);
  316. return Ctor;
  317. });
  318. Ctor.prototype.mixin = function(key, value) {
  319. Ctor.prototype[key] = value;
  320. return this;
  321. };
  322. return Base;
  323. }));
  324. /**
  325. * Used for adding methods to the `Base` prototype, and/or to the prototype of child instances.
  326. * When a mixin function returns a function, the returned function is pushed onto the `.mixins`
  327. * array, making it available to be used on inheriting classes whenever `Base.mixins()` is
  328. * called (e.g. `Base.mixins(Child)`).
  329. *
  330. * ```js
  331. * Base.mixin(function(proto) {
  332. * proto.foo = function(msg) {
  333. * return 'foo ' + msg;
  334. * };
  335. * });
  336. * ```
  337. * @name #mixin
  338. * @param {Function} `fn` Function to call
  339. * @return {Object} Returns the `Base` constructor for chaining
  340. * @api public
  341. */
  342. define(Base, 'mixin', function(fn) {
  343. var mixin = fn(Base.prototype, Base);
  344. if (typeof mixin === 'function') {
  345. Base.prototype.mixins.push(mixin);
  346. }
  347. return Base;
  348. });
  349. /**
  350. * Static method for running global mixin functions against a child constructor.
  351. * Mixins must be registered before calling this method.
  352. *
  353. * ```js
  354. * Base.extend(Child);
  355. * Base.mixins(Child);
  356. * ```
  357. * @name #mixins
  358. * @param {Function} `Child` Constructor function of a child class
  359. * @return {Object} Returns the `Base` constructor for chaining
  360. * @api public
  361. */
  362. define(Base, 'mixins', function(Child) {
  363. Base.run(Child, 'mixin', Base.prototype.mixins);
  364. return Base;
  365. });
  366. /**
  367. * Similar to `util.inherit`, but copies all static properties, prototype properties, and
  368. * getters/setters from `Provider` to `Receiver`. See [class-utils][]{#inherit} for more details.
  369. *
  370. * ```js
  371. * Base.inherit(Foo, Bar);
  372. * ```
  373. * @name #inherit
  374. * @param {Function} `Receiver` Receiving (child) constructor
  375. * @param {Function} `Provider` Providing (parent) constructor
  376. * @return {Object} Returns the `Base` constructor for chaining
  377. * @api public
  378. */
  379. define(Base, 'inherit', cu.inherit);
  380. define(Base, 'bubble', cu.bubble);
  381. return Base;
  382. }
  383. /**
  384. * Expose `Base` with default settings
  385. */
  386. module.exports = namespace();
  387. /**
  388. * Allow users to define a namespace
  389. */
  390. module.exports.namespace = namespace;