UNPKG

2.17 kBJavaScriptView Raw
1'use strict';
2
3var Base = require('base');
4var debug = require('debug')('base:templates:group');
5var utils = require('./utils');
6
7/**
8 * Expose `Group`
9 */
10
11module.exports = exports = Group;
12
13/**
14 * Create an instance of `Group` with the given `options`.
15 *
16 * ```js
17 * var group = new Group({
18 * 'foo': { items: [1,2,3] }
19 * });
20 * ```
21 * @param {Object} `options`
22 * @api public
23 */
24
25function Group(config) {
26 if (!(this instanceof Group)) {
27 return new Group(config);
28 }
29
30 Base.call(this, config);
31 this.is('Group');
32 this.use(utils.option());
33 this.use(utils.plugin());
34 this.init();
35}
36
37/**
38 * Inherit `Base`
39 */
40
41Base.extend(Group);
42
43/**
44 * Initialize Group defaults. Makes `options` and `cache`
45 * (inherited from `Base`) non-emumerable.
46 */
47
48Group.prototype.init = function() {
49 debug('initializing');
50 var opts = {};
51
52 Object.defineProperty(this, 'options', {
53 configurable: true,
54 enumerable: false,
55 set: function(val) {
56 opts = val;
57 },
58 get: function() {
59 return opts || {};
60 }
61 });
62
63 this.define('cache', this.cache);
64 this.define('List', this.List || require('./list'));
65};
66
67/**
68 * Get a value from the group instance. If the value is an array,
69 * it will be returned as a new `List`.
70 */
71
72Group.prototype.get = function() {
73 var res = Base.prototype.get.apply(this, arguments);
74 if (Array.isArray(res)) {
75 var List = this.List;
76 var list = new List();
77 list.addItems(res);
78 return list;
79 }
80 handleErrors(this, res);
81 return res;
82};
83
84/**
85 * When `get` returns a non-Array object, we decorate
86 * noop `List` methods onto the object to throw errors when list methods
87 * are used, since list array methods do not work on groups.
88 *
89 * @param {Object} `group`
90 * @param {Object} `val` Value returned from `group.get()`
91 */
92
93function handleErrors(group, val) {
94 if (utils.isObject(val)) {
95 var List = group.List;
96 var keys = Object.keys(List.prototype);
97
98 keys.forEach(function(key) {
99 if (typeof val[key] !== 'undefined') return;
100
101 utils.define(val, key, function() {
102 throw new Error(key + ' can only be used with an array of `List` items.');
103 });
104 });
105 }
106}