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