rasti 1.1.3 → 2.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,445 @@
1
+ function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
2
+ function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
3
+ function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
4
+ import View from './View';
5
+
6
+ // This options keys will be extended on view instance.
7
+ var componentOptions = {
8
+ key: true,
9
+ state: true,
10
+ onCreate: true,
11
+ onChange: true,
12
+ onRender: true
13
+ };
14
+
15
+ /*
16
+ * Helper function. Extract attributes from html tag
17
+ * @param text {string} html text
18
+ * @return {object} Object with keys / values representing attributes.
19
+ */
20
+ var getAttributes = function getAttributes(text) {
21
+ var attributes = {};
22
+ var re = /([a-z]+)=?(\S+)?/gi;
23
+ var result;
24
+ while ((result = re.exec(text)) !== null) {
25
+ attributes[result[1]] = result[2] ? result[2].replace(/'|"/g, '') : true;
26
+ }
27
+ return attributes;
28
+ };
29
+
30
+ /*
31
+ * Helper function. If first arg is a placeholder for an expression, return the expression.
32
+ */
33
+ var getExpression = function getExpression(placeholder, expressions) {
34
+ var match = placeholder.match(new RegExp(Component.EXPRESSION_PLACEHOLDER_TEMPLATE('(\\d+)')));
35
+ return match && match[1] ? expressions[match[1]] : placeholder;
36
+ };
37
+
38
+ /*
39
+ * Helper function. If expression is a function, call it with context and args.
40
+ */
41
+ var evalExpression = function evalExpression(expression, context) {
42
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
43
+ args[_key - 2] = arguments[_key];
44
+ }
45
+ return typeof expression === 'function' ? expression.apply(context, args) : expression;
46
+ };
47
+
48
+ /**
49
+ * Components are a special kind of `View` that is designed to be easily composable,
50
+ * making it simple to add child views and build complex user interfaces.<br />
51
+ * Unlike views, which are render-agnostic, components have a specific set of rendering
52
+ * guidelines that allow for a more declarative development style.<br />
53
+ * Components are defined with the `create` static method, which takes a tagged template.
54
+ * @module
55
+ * @extends Rasti.View
56
+ * @param {object} options Object containing options. The following keys will be merged to `this`: model, state, key, onDestroy, onRender, onCreate, onChange.
57
+ * @property {string} key A unique key to identify the component. Used to recycle child components.
58
+ * @property {object} model A `Rasti.Model` or any emitter object containing data and business logic.
59
+ * @property {object} state A `Rasti.Model` or any emitter object containing data and business logic, to be used as internal state.
60
+ * @example
61
+ * import { Component, Model } from 'rasti';
62
+ * // Create Timer component.
63
+ * const Timer = Component.create`
64
+ * <div>
65
+ * Seconds: <span>${({ model }) => model.seconds}</span>
66
+ * </div>
67
+ * `;
68
+ * // Create model to store seconds.
69
+ * const model = new Model({ seconds: 0 });
70
+ * // Mount timer on body.
71
+ * Timer.mount({ model }, document.body);
72
+ * // Increment `model.seconds` every second.
73
+ * setInterval(() => model.seconds++, 1000);
74
+ */
75
+ var Component = /*#__PURE__*/function (_View) {
76
+ _inheritsLoose(Component, _View);
77
+ function Component() {
78
+ var _this;
79
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
80
+ _this = _View.call(this, options) || this;
81
+ // Extend "this" with options, mapping componentOptions keys.
82
+ Object.keys(options).forEach(function (key) {
83
+ if (componentOptions[key]) _this[key] = options[key];
84
+ });
85
+ // Store options by default.
86
+ _this.options = options;
87
+ // Ensure id.
88
+ _this.id = _this.attributes.id ?
89
+ // If id is provided, evaluate it.
90
+ evalExpression(_this.attributes.id, _assertThisInitialized(_this), _assertThisInitialized(_this)) :
91
+ // Generate a unique id and set it as id attribute.
92
+ Component.ID_TEMPLATE(_this.uid);
93
+ // Bind onChange to this to be used as listener.
94
+ // Store bound version, so it can be removed on onDestroy method.
95
+ _this.onChange = _this.onChange.bind(_assertThisInitialized(_this));
96
+ // Listen to model changes and call onChange.
97
+ if (_this.model) _this.model.on('change', _this.onChange);
98
+ if (_this.state) _this.state.on('change', _this.onChange);
99
+ // Call life cycle method.
100
+ _this.onCreate.apply(_assertThisInitialized(_this), arguments);
101
+ return _this;
102
+ }
103
+
104
+ /*
105
+ * Override. We don't want to ensure an element on instantiation.
106
+ * We will provide it later.
107
+ */
108
+ var _proto = Component.prototype;
109
+ _proto.ensureElement = function ensureElement() {
110
+ // If el is provided, delegate events.
111
+ if (this.el) this.delegateEvents();
112
+ };
113
+ _proto.findElement = function findElement(parent) {
114
+ return (parent || document).querySelector("#" + this.id);
115
+ }
116
+
117
+ /*
118
+ * Used internally on the render process. Attach the view to the dom element.
119
+ */;
120
+ _proto.hydrate = function hydrate(parent) {
121
+ var _this2 = this;
122
+ this.el = this.findElement(parent);
123
+ this.delegateEvents();
124
+ this.children.forEach(function (child) {
125
+ return child.hydrate(_this2.el);
126
+ });
127
+ this.onRender.call(this);
128
+ }
129
+
130
+ /*
131
+ * Override. Add some custom logic to super `destroy` method.
132
+ */;
133
+ _proto.destroy = function destroy(options) {
134
+ _View.prototype.destroy.call(this, options);
135
+ // Stop listening to `change`.
136
+ // Set destroyed flag to prevent a last render after destroyed. TODO: Review
137
+ if (this.model) this.model.off('change', this.onChange);
138
+ if (this.state) this.state.off('change', this.onChange);
139
+ this.destroyed = true;
140
+ }
141
+
142
+ /**
143
+ * Lifecycle method. Called when the view is created at the end of the constructor.
144
+ * @param options {object} The view options.
145
+ */;
146
+ _proto.onCreate = function onCreate() {}
147
+
148
+ /**
149
+ * Lifecycle method. Called when model emits `change` event.
150
+ * By default calls render method.
151
+ * This method should be extended with custom logic.
152
+ * Maybe comparing new attributes with previous ones and calling
153
+ * render when needed. Or doing some dom transformation.
154
+ * @param model {Rasti.Model}
155
+ * @param key {string}
156
+ * @param value {any}
157
+ */;
158
+ _proto.onChange = function onChange() {
159
+ this.render();
160
+ }
161
+
162
+ /**
163
+ * Lifecycle method. Called when the view is rendered.
164
+ */;
165
+ _proto.onRender = function onRender() {}
166
+
167
+ /**
168
+ * Lifecycle method. Called when the view is destroyed.
169
+ */;
170
+ _proto.onDestroy = function onDestroy() {}
171
+
172
+ /*
173
+ * Replace expressions.
174
+ */;
175
+ _proto.replaceExpressions = function replaceExpressions(string, addChild) {
176
+ var _this3 = this;
177
+ return string.replace(new RegExp(Component.EXPRESSION_PLACEHOLDER_TEMPLATE('(\\d+)'), 'g'), function (match) {
178
+ var expression = getExpression(match, _this3.template.expressions);
179
+ // Eval expression. Pass view as argument.
180
+ var result = evalExpression(expression, _this3, _this3);
181
+ // Treat all expressions as arrays.
182
+ var results = result instanceof Array ? result : [result];
183
+ // Replace expression with the result of the evaluation.
184
+ return results.reduce(function (out, result) {
185
+ var parsed;
186
+ // If result is true, replace it with a placeholder.
187
+ if (result === true) parsed = Component.TRUE_PLACEHOLDER;
188
+ // If result is false, replace it with a placeholder.
189
+ else if (result === false) parsed = Component.FALSE_PLACEHOLDER;
190
+ // Replace null or undefined with empty string.
191
+ else if (result === null || typeof result === 'undefined') parsed = '';
192
+ // If result is a view, call addChild callback.
193
+ else if (result && typeof result.render === 'function') parsed = addChild(result);
194
+ // Return expression itself.
195
+ else parsed = result;
196
+ // Concatenate expressions.
197
+ return out + parsed;
198
+ }, '');
199
+ })
200
+ // Replace `attribute="true"` with `attribute`
201
+ .replace(new RegExp("([a-z]+)=[\"|']" + Component.TRUE_PLACEHOLDER + "[\"|']", 'g'), '$1')
202
+ // Replace `attribute="false"` with empty string.
203
+ .replace(new RegExp("([a-z]+)=[\"|']" + Component.FALSE_PLACEHOLDER + "[\"|']", 'g'), '')
204
+ // Replace rest of false expressions with empty string.
205
+ .replace(new RegExp(Component.FALSE_PLACEHOLDER, 'g'), '');
206
+ }
207
+
208
+ /*
209
+ * Treat the whole view as a HTML string.
210
+ */;
211
+ _proto.toString = function toString() {
212
+ var _this4 = this;
213
+ // Normally there won't be any children, but if there are, destroy them.
214
+ this.destroyChildren();
215
+ // Add id to template including root element (this.el) as part of it.
216
+ var tpl = this.attributes.id ? this.template.outer : this.template.outer.replace(/^<([a-z]+)/, "<$1 id=\"" + this.id + "\"");
217
+ // Replace expressions.
218
+ return this.replaceExpressions(tpl, function (component) {
219
+ // Add child component.
220
+ return _this4.addChild(component);
221
+ });
222
+ }
223
+
224
+ /*
225
+ * View render method.
226
+ */;
227
+ _proto.render = function render() {
228
+ var _this5 = this;
229
+ // Prevent a last re render if view is already destroyed.
230
+ if (this.destroyed) return this;
231
+ // If "this.el" is not present,
232
+ // create a new element according "this.tag"
233
+ // and "this.attributes".
234
+ if (!this.el) {
235
+ this.el = this.createElement(this.tag);
236
+ this.delegateEvents();
237
+ }
238
+ // Set `this.el` attributes.
239
+ Object.keys(this.attributes).forEach(function (key) {
240
+ // Omit changing id.
241
+ if (key === 'id') return;
242
+ // Evaluate attribute value.
243
+ var value = evalExpression(_this5.attributes[key], _this5, _this5);
244
+ // Transform bool attribute values
245
+ if (value === false) {
246
+ // Remove false attributes.
247
+ _this5.el.removeAttribute(key);
248
+ } else {
249
+ if (value === true) value = '';
250
+ _this5.el.setAttribute(key, value);
251
+ }
252
+ });
253
+
254
+ // Check for `template.inner`.
255
+ // Root element may be a self enclosed tag element without innerHTML.
256
+ if (this.template.inner) {
257
+ var previousChildren = this.children;
258
+ this.children = [];
259
+ var nextChildren = [];
260
+ var recycledChildren = [];
261
+
262
+ // Replace expressions.
263
+ // Set html text inside `this.el`. Make it part of the dom.
264
+ this.el.innerHTML = this.replaceExpressions(this.template.inner, function (component) {
265
+ var out = component;
266
+ // Check if child already exists.
267
+ var found = component.key && previousChildren.find(function (previousChild) {
268
+ return previousChild.key === component.key;
269
+ });
270
+ if (found) {
271
+ // If child already exists, replace it html by its root element.
272
+ out = "<" + found.tag + " id=\"" + found.id + "\"></" + found.tag + ">";
273
+ // Add child to recycled children.
274
+ recycledChildren.push(found);
275
+ // Destroy new child component. Use recycled one instead.
276
+ component.destroy();
277
+ } else {
278
+ // Not found. Add new child component.
279
+ nextChildren.push(component);
280
+ }
281
+ // Component html.
282
+ return out;
283
+ });
284
+ // Add new children. Hydrate them.
285
+ nextChildren.forEach(function (nextChild) {
286
+ _this5.addChild(nextChild).hydrate(_this5.el);
287
+ });
288
+ // Replace children root elements with recycled components.
289
+ recycledChildren.forEach(function (recycledChild) {
290
+ _this5.el.replaceChild(_this5.addChild(recycledChild).el, recycledChild.findElement(_this5.el));
291
+ });
292
+ // Destroy unused children.
293
+ previousChildren.forEach(function (previousChild) {
294
+ var found = recycledChildren.indexOf(previousChild) > -1;
295
+ if (!found) previousChild.destroy();
296
+ });
297
+ }
298
+ // Call onRender lifecycle method.
299
+ this.onRender.call(this);
300
+ // Return this for chaining.
301
+ return this;
302
+ }
303
+
304
+ /**
305
+ * Helper method used to extend a `Component`, creating a subclass.
306
+ * @static
307
+ * @param {object} object Object containing methods to be added to the new `Component` subclass. Also can be a function that receives the parent prototype and returns an object.
308
+ */;
309
+ Component.extend = function extend(object) {
310
+ var Current = this;
311
+ var Extended = /*#__PURE__*/function (_Current) {
312
+ _inheritsLoose(Extended, _Current);
313
+ function Extended() {
314
+ return _Current.apply(this, arguments) || this;
315
+ }
316
+ return Extended;
317
+ }(Current);
318
+ Object.assign(Extended.prototype, typeof object === 'function' ? object(Current.prototype) : object);
319
+ return Extended;
320
+ }
321
+
322
+ /**
323
+ * Mount the component into the dom.
324
+ * It instantiate the Component view using options,
325
+ * appends its element into the DOM (if `el` is provided).
326
+ * And returns the view instance.
327
+ * @static
328
+ * @param {object} options The view options.
329
+ * @param {node} el Dom element to append the view element.
330
+ * @param {boolean} hydrate If true, the view will use existing html.
331
+ * @return {Rasti.Component}
332
+ */;
333
+ Component.mount = function mount() {
334
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
335
+ var el = arguments.length > 1 ? arguments[1] : undefined;
336
+ var hydrate = arguments.length > 2 ? arguments[2] : undefined;
337
+ // Instantiate view.
338
+ var view = new this(options);
339
+
340
+ // If `el` is passed, mount component.
341
+ if (el) {
342
+ if (hydrate) {
343
+ view.toString();
344
+ } else {
345
+ var fragment = document.createElement('template');
346
+ // Add html text into element inner html.
347
+ fragment.innerHTML = view;
348
+ // Add to dom.
349
+ el.appendChild(fragment.content);
350
+ }
351
+ view.hydrate(el);
352
+ }
353
+ return view;
354
+ }
355
+ /**
356
+ * Takes a tagged template containing an HTML string,
357
+ * and returns a new `Component` class.
358
+ * - The template outer tag and attributes will be used to create the view's root element.
359
+ * - Boolean attributes should be passed in the form of `attribute="${() => true}"`.
360
+ * - Event handlers should be passed, at the root element, in the form of `onEventName=${{'selector' : listener }}`. Where `selector` is a css selector. The event will be delegated to the view's root element.
361
+ * - The template inner HTML will be used as the view's template.
362
+ * - Template interpolations that are functions will be evaluated on the render process. Receiving the view instance as argument. And being bound to it.
363
+ * - If the function returns `null`, `undefined`, `false` or empty string, the interpolation won't render any content.
364
+ * - If the function returns a component instance, it will be added as a child component.
365
+ * - If the function returns an array, each item will be evaluated as above.
366
+ * @static
367
+ * @param {string} HTML template for the component.
368
+ * @return {Rasti.Component}
369
+ */;
370
+ Component.create = function create(strings) {
371
+ for (var _len2 = arguments.length, expressions = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
372
+ expressions[_key2 - 1] = arguments[_key2];
373
+ }
374
+ var parts = [];
375
+ // Replace functions and objects interpolations with `{number}`.
376
+ // Where `number` is the index on expressions array.
377
+ strings.forEach(function (string, i) {
378
+ // Add string part.
379
+ parts.push(string);
380
+ // Add expression placeholder for later or expression eval.
381
+ if (expressions[i]) {
382
+ parts.push(typeof expressions[i] === 'function' || typeof expressions[i] === 'object' ? Component.EXPRESSION_PLACEHOLDER_TEMPLATE(i) : expressions[i]);
383
+ }
384
+ });
385
+ // Create output text for main template.
386
+ var main = parts.join('').trim().replace(/\n/g, '');
387
+ // Extract outer tag, attributes and inner html.
388
+ var result = main.match(/^<([a-z]+)(.*?)>(.*)<\/\1>$/) || main.match(/^<([a-z]+)(.*?)\/>$/);
389
+ // Remove events listeners.
390
+ var string = main.replace(/on([A-Z]{1}[a-z]+)+=[^>\s]+/g, '');
391
+ // Parse attributes from html text into an object.
392
+ var attributes = getAttributes(result[2]);
393
+ // Events to be delegated.
394
+ var events = {};
395
+ // Filter events. To generate events object.
396
+ // Generate attributes object, replace placeholders with expressions.
397
+ attributes = Object.keys(attributes).reduce(function (out, key) {
398
+ // Is Event?
399
+ var matchKey = key.match(/on(([A-Z]{1}[a-z]+)+)/);
400
+ // Is placeholder for function or object?
401
+ // Get expression or value.
402
+ var value = getExpression(attributes[key], expressions);
403
+ // Is event handler. Add to events object.
404
+ if (matchKey && matchKey[1]) {
405
+ var eventType = matchKey[1].toLowerCase();
406
+ Object.keys(value).forEach(function (selector) {
407
+ return events["" + eventType + (selector === '&' ? '' : " " + selector)] = value[selector];
408
+ });
409
+ return out;
410
+ }
411
+ // Is attribute. Add to attributes object.
412
+ out[key] = value;
413
+ return out;
414
+ }, {});
415
+ var Current = this;
416
+ // Create subclass for this component.
417
+ return Current.extend({
418
+ // Set events.
419
+ events: events,
420
+ // Set attributes.
421
+ attributes: attributes,
422
+ // Set template data.
423
+ template: {
424
+ // Template including root element (this.el) as part of the template.
425
+ outer: string,
426
+ // Template for innerHTML of root element.
427
+ inner: result[3],
428
+ // Template expressions.
429
+ expressions: expressions
430
+ },
431
+ // Set root element tag.
432
+ tag: result[1]
433
+ });
434
+ };
435
+ return Component;
436
+ }(View);
437
+ export { Component as default };
438
+ Component.ID_TEMPLATE = function (uid) {
439
+ return "rasti-component-" + uid;
440
+ };
441
+ Component.EXPRESSION_PLACEHOLDER_TEMPLATE = function (idx) {
442
+ return "__RASTI_EXPRESSION{" + idx + "}";
443
+ };
444
+ Component.TRUE_PLACEHOLDER = '__RASTI_TRUE';
445
+ Component.FALSE_PLACEHOLDER = '__RASTI_FALSE';
package/es/Emitter.js CHANGED
@@ -1,21 +1,39 @@
1
1
  /**
2
- * Emitter is a class that can be extended giving the subclass the ability to emit
3
- * and bind custom named events. Model and View inherits from it.
2
+ * `Emitter` is a class that provides an easy way to implement the observer pattern
3
+ * in your applications.<br />
4
+ * It can be extended to create new classes that have the ability to emit and bind custom named events.<br />
5
+ * Emitter is used by `Model` and `View` classes, which inherit from it to implement
6
+ * event-driven functionality.
7
+ *
4
8
  * @module
5
9
  * @example
6
10
  * import { Emitter } from 'rasti';
7
- * // Define App class, inherits from Emitter.
8
- * class App extends Emitter {
11
+ * // Custom cart
12
+ * class ShoppingCart extends Emitter {
9
13
  * constructor() {
10
- * super()
11
- * // Fetch data and emit `ready` event.
12
- * fetch('/api/init').then(() => this.emit('ready'));
14
+ * super();
15
+ * this.items = [];
16
+ * }
17
+ *
18
+ * addItem(item) {
19
+ * this.items.push(item);
20
+ * // Emit a custom event called `itemAdded`.
21
+ * // Pass the added item as an argument to the event listener.
22
+ * this.emit('itemAdded', item);
13
23
  * }
14
24
  * }
15
- * // Instantiate App.
16
- * const app = new App();
17
- * // Add event listener to ready event.
18
- * app.on('ready', () => console.log('app is ready!'));
25
+ * // Create an instance of ShoppingCart and Logger
26
+ * const cart = new ShoppingCart();
27
+ * // Listen to the `itemAdded` event and log the added item using the logger.
28
+ * cart.on('itemAdded', (item) => {
29
+ * console.log(`Item added to cart: ${item.name} - Price: $${item.price}`);
30
+ * });
31
+ * // Simulate adding items to the cart
32
+ * const item1 = { name : 'Smartphone', price : 1000 };
33
+ * const item2 = { name : 'Headphones', price : 150 };
34
+ *
35
+ * cart.addItem(item1); // Output: "Item added to cart: Smartphone - Price: $1000"
36
+ * cart.addItem(item2); // Output: "Item added to cart: Headphones - Price: $150"
19
37
  */
20
38
  var Emitter = /*#__PURE__*/function () {
21
39
  function Emitter() {}
package/es/Model.js CHANGED
@@ -6,37 +6,46 @@ import Emitter from './Emitter';
6
6
  * - Orchestrates data and business logic.
7
7
  * - Emits events when data changes.
8
8
  *
9
- * A Model manages an internal table of data attributes, and triggers "change" events
10
- * when any of its data is modified.<br />
11
- * Models may handle syncing data with a persistence layer.<br />
12
- * Design your models as the atomic reusable objects containing all of the helpful functions for
13
- * manipulating their particular bit of data.<br />
14
- * Models should be able to be passed around throughout your app, and used anywhere that bit of data is needed.<br />
15
- * Rasti Models stores its attributes in `this.attributes`, which is extended from `this.defaults` and constructor `attrs` parameter.
16
- * For every attribute, a getter is generated, which retrieve the model property from `this.attributes`.
17
- * And a setter, which sets the model property in `this.attributes` and emits `change` and `change:attribute` events.
9
+ * A `Model` manages an internal table of data attributes and triggers change events when any of its data is modified.<br />
10
+ * Models may handle syncing data with a persistence layer. To design your models, create atomic, reusable objects
11
+ * that contain all the necessary functions for manipulating their specific data.<br />
12
+ * Models should be easily passed throughout your app and used anywhere the corresponding data is needed.<br />
13
+ * Rasti models stores its attributes in `this.attributes`, which is extended from `this.defaults` and the
14
+ * constructor `attrs` parameter. For every attribute, a getter is generated to retrieve the model property
15
+ * from `this.attributes`, and a setter is created to set the model property in `this.attributes` and emit `change`
16
+ * and `change:attribute` events.
18
17
  * @module
18
+ * @extends Rasti.Emitter
19
19
  * @param {object} attrs Object containing model attributes to extend `this.attributes`. Getters and setters are generated for `this.attributtes`, in order to emit `change` events.
20
20
  * @example
21
- * // Todo model
22
- * class TodoModel extends Rasti.Model {
23
- * toggle() {
24
- * // Set completed property. This will call a setter that will set `completed`
25
- * // in this.attributes, and emit `change` and `change:completed` events.
26
- * this.completed = !this.completed;
21
+ * import { Model } from 'rasti';
22
+ * // Product model
23
+ * class ProductModel extends Model {
24
+ * preinitialize() {
25
+ * // The Product model has `name` and `price` default attributes.
26
+ * // `defaults` will extend `this.attributes`.
27
+ * // Getters and setters are generated for `this.attributes`,
28
+ * // in order to emit `change` events.
29
+ * this.defaults = {
30
+ * name: '',
31
+ * price: 0
32
+ * };
33
+ * }
34
+ *
35
+ * setDiscount(discountPercentage) {
36
+ * // Apply a discount to the price property.
37
+ * // This will call a setter that will update `price` in `this.attributes`,
38
+ * // and emit `change` and `change:price` events.
39
+ * const discount = this.price * (discountPercentage / 100);
40
+ * this.price -= discount;
27
41
  * }
28
42
  * }
29
- * // Todo model has `title` and `completed` default attributes. `defaults` will extend `this.attributes`. Getters and setters are generated for `this.attributtes`, in order to emit `change` events.
30
- * TodoModel.prototype.defaults = {
31
- * title : '',
32
- * completed : false
33
- * };
34
- * // Create todo. Pass `title` attribute as argument.
35
- * const todo = new TodoModel({ title : 'Learn Rasti' });
36
- * // Listen to `change:completed` event.
37
- * todo.on('change:completed', () => console.log('Completed:', todo.completed));
38
- * // Complete todo.
39
- * todo.toggle(); // Completed: true
43
+ * // Create a product instance with a name and price.
44
+ * const product = new ProductModel({ name: 'Smartphone', price: 1000 });
45
+ * // Listen to the `change:price` event.
46
+ * product.on('change:price', () => console.log('New Price:', product.price));
47
+ * // Apply a 10% discount to the product.
48
+ * product.setDiscount(10); // Output: "New Price: 900"
40
49
  */
41
50
  var Model = /*#__PURE__*/function (_Emitter) {
42
51
  _inheritsLoose(Model, _Emitter);
package/es/View.js CHANGED
@@ -19,13 +19,15 @@ var viewOptions = {
19
19
  * - Handles user input and interactivity.
20
20
  * - Sends captured input to the model.
21
21
  *
22
- * A View is an atomic chunk of user interface. It often renders the data from a specific model,
23
- * or number of models, but views can also be data-less chunks of UI that stand alone.<br />
24
- * Models must be unaware of views. Instead, views listen to the model "change" events,
25
- * and react or re-render themselves appropriately.<br />
26
- * Views has a root element, `this.el`. That element is used for event delegation. Elements lookups are scoped to that element. And render and dom manipulations should be done inside that element.
27
- * If `this.el` is not present, an element will be created using `this.tag` (or `div` as default), and `this.attributes`.<br />
22
+ * A `View` is an atomic unit of the user interface that can render the data from a specific model or multiple models.
23
+ * However, views can also be independent and have no associated data.<br />
24
+ * Models must be unaware of views. Views, on the other hand, may render model data and listen to the change events
25
+ * emitted by the models to re-render themselves based on changes.<br />
26
+ * Each `View` has a root element, `this.el`, which is used for event delegation.<br />
27
+ * All element lookups are scoped to this element, and any rendering or DOM manipulations should be done inside it.
28
+ * If `this.el` is not present, an element will be created using `this.tag` (defaulting to div) and `this.attributes`.
28
29
  * @module
30
+ * @extends Rasti.Emitter
29
31
  * @param {object} options Object containing options. The following keys will be merged to `this`: el, tag, attributes, events, model, template, onDestroy.
30
32
  * @property {node} el Every view has a root element, `this.el`. If not present it will be created.
31
33
  * @property {string} tag If `this.el` is not present, an element will be created using `this.tag`. Default is `div`.
@@ -34,43 +36,25 @@ var viewOptions = {
34
36
  * @property {object} model A `Rasti.Model` or any object containing data and business logic.
35
37
  * @property {function} template A function that receives data and returns a markup string (html for example).
36
38
  * @example
37
- * // Counter view.
38
- * class CounterView extends View {
39
+ * import { View } from 'rasti';
40
+ *
41
+ * class Timer extends View {
39
42
  * constructor(options) {
40
43
  * super(options);
41
- * // Bind method to `this`, to be called as listener.
42
- * this.render = this.render.bind(this);
43
- * // Listen to model change and re render.
44
- * this.model.on('change:count', this.render);
44
+ * // Create model to store internal state. Set `seconds` attribute into 0.
45
+ * this.model = new Model({ seconds : 0 });
46
+ * // Listen to changes in model `seconds` attribute and re render.
47
+ * this.model.on('change:seconds', this.render.bind(this));
48
+ * // Increment model `seconds` attribute every 1000 milliseconds.
49
+ * this.interval = setInterval(() => this.model.seconds++, 1000);
45
50
  * }
46
- * onDestroy() {
47
- * // Unbind events when destroyed.
48
- * this.model.off('change:count', this.render);
49
- * }
50
- * // Listener method. Called when button is clicked.
51
- * onClickIncrement() {
52
- * // Increment count on model.
53
- * this.model.count++;
51
+ *
52
+ * template(model) {
53
+ * return `Seconds: <span>${model.seconds}</span>`;
54
54
  * }
55
55
  * }
56
- * Object.assign(CounterView.prototype, {
57
- * // Set delegated events.
58
- * // Call `onClickIncrement` when button is clicked.
59
- * events : {
60
- * 'click button' : 'onClickIncrement'
61
- * },
62
- * // View's template.
63
- * template : (model) => `
64
- * <div>The count is: ${model.count}</div>
65
- * <button>Increment</button>
66
- * `
67
- * });
68
- * // Model.
69
- * const model = new Model({ count : 0 });
70
- * // Instantiate CounterView.
71
- * const counterView = new CounterView({ model });
72
- * // Add to DOM.
73
- * document.body.appendChild(counterView.render().el);
56
+ * // Render view and append view's element into body.
57
+ * document.body.appendChild(new Timer().render().el);
74
58
  */
75
59
  var View = /*#__PURE__*/function (_Emitter) {
76
60
  _inheritsLoose(View, _Emitter);
@@ -143,7 +127,7 @@ var View = /*#__PURE__*/function (_Emitter) {
143
127
  // Remove `this.el` if "options.remove" is true.
144
128
  if (remove) this.removeElement();
145
129
  // Call onDestroy lifecycle method
146
- this.onDestroy();
130
+ this.onDestroy.apply(this, arguments);
147
131
  }
148
132
 
149
133
  /**
package/es/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import Emitter from './Emitter.js';
2
2
  import Model from './Model.js';
3
3
  import View from './View.js';
4
- export { Emitter, Model, View };
4
+ import Component from './Component.js';
5
+ export { Emitter, Model, View, Component };