Browse code

init v1

Louis Jonget authored on13/05/2024 20:43:46
Showing1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,78 @@
1
+'use strict';
2
+
3
+var componentRegistry = require('./component-registry');
4
+var minified = require('../vendor/minified');
5
+var utils = require('../lib/utils');
6
+var ClayEvents = require('./clay-events');
7
+
8
+var _ = minified._;
9
+var HTML = minified.HTML;
10
+
11
+/**
12
+ * @extends ClayEvents
13
+ * @param {Clay~ConfigItem} config
14
+ * @constructor
15
+ */
16
+function ClayItem(config) {
17
+  var self = this;
18
+
19
+  var _component = componentRegistry[config.type];
20
+
21
+  if (!_component) {
22
+    throw new Error('The component: ' + config.type + ' is not registered. ' +
23
+                    'Make sure to register it with ClayConfig.registerComponent()');
24
+  }
25
+
26
+  var extra = {
27
+    i18n: {
28
+      foo: 'bar'
29
+    }
30
+  };
31
+  var _templateData = _.extend({}, _component.defaults || {}, config, extra);
32
+  var _html = _.formatHtml(_component.template.trim(), _templateData);
33
+
34
+  /** @type {string|null} */
35
+  self.id = config.id || null;
36
+
37
+  /** @type {string|null} */
38
+  self.messageKey = config.messageKey || null;
39
+
40
+  /** @type {Object} */
41
+  self.config = config;
42
+  /** @type {M} */
43
+  self.$element = HTML(_html, _templateData);
44
+
45
+  /** @type {M} */
46
+  self.$manipulatorTarget = self.$element.select('[data-manipulator-target]');
47
+
48
+  // this caters for situations where the manipulator target is the root element
49
+  if (!self.$manipulatorTarget.length) {
50
+    self.$manipulatorTarget = self.$element;
51
+  }
52
+
53
+  /**
54
+   * Run the initializer if it exists and attaches the css to the head.
55
+   * Passes minified as the first param
56
+   * @param {ClayConfig} clay
57
+   * @returns {ClayItem}
58
+   */
59
+  self.initialize = function(clay) {
60
+    if (typeof _component.initialize === 'function') {
61
+      _component.initialize.call(self, minified, clay);
62
+    }
63
+    return self;
64
+  };
65
+
66
+  // attach event methods
67
+  ClayEvents.call(self, self.$manipulatorTarget);
68
+
69
+  // attach the manipulator methods to the clayItem
70
+  _.eachObj(_component.manipulator, function(methodName, method) {
71
+    self[methodName] = method.bind(self);
72
+  });
73
+
74
+  // prevent external modifications of properties
75
+  utils.updateProperties(self, { writable: false, configurable: false });
76
+}
77
+
78
+module.exports = ClayItem;