rasti 1.1.2 → 2.0.0-alpha.0

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