1 | 'use strict';
|
2 |
|
3 | var Base = require('base');
|
4 | var debug = require('debug')('base:templates:group');
|
5 | var utils = require('./utils');
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | module.exports = exports = Group;
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | function 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 |
|
39 |
|
40 |
|
41 | Base.extend(Group);
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 | Group.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 |
|
69 |
|
70 |
|
71 |
|
72 | Group.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 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 | function 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 | }
|