For pages whose HTML already exists: server-rendered apps, widgets, old code, a single HTML file. Add one <script> tag, bind object properties to nodes in JavaScript, keep the markup as it is. Since 2013; 3.0 is one package with ES modules and TypeScript types, and zero dependencies.
Size:matreshka.min.js is 75.0 kB minified, 24.3 kB with gzip and 21.5 kB with brotli, the compression a CDN uses for current browsers.
Matreshka.js connects JavaScript objects to the HTML a page already has. You bind a property to a DOM node, and from then on they stay in sync. Set the property and the node updates; type into the node and the property changes. There are no templates, no virtual DOM and no build step.
Binding a property gives it a getter and a setter. Assigning app.x = 'hi' runs the setter, which updates every node bound to x and fires a change:x event. Computed properties, value transforms and collections are all built on this one mechanism.
const app = new Matreshka();app.bindNode('name', '.name'); // <input class="name">app.bindNode('name', '.out', Matreshka.binders.text()); // <span class="out">app.name = 'Ann'; // the input and the span show "Ann"// type "Bob" in the input → app.name is 'Bob', the span shows "Bob"
A component framework. It has no JSX, no single-file components and no server rendering. If you build the whole UI in JavaScript from scratch, React or Vue fit better.
import Matreshka from 'matreshka';// or, with CommonJS (Node.js 22.12+)const { Matreshka } = require('matreshka');
The router and the form parser are in the same package: matreshka/router binds properties to parts of the URL, matreshka/parse-form binds named form fields to properties.
initRouter(object, '/a/b/') keeps object.a and object.b in sync with the parts of location.hash after #! (#!/foo/bar/); the values are encoded in the URL and decoded in the properties. Pass 'history' as the third argument to use the path through the History API instead. parseForm(object, form) returns the form, or null when the form isn't found. More: Matreshka.initRouter, Matreshka.parseForm.
import { initRouter } from 'matreshka/router';import { parseForm } from 'matreshka/parse-form';
Without a bundler, load the browser bundle. It defines the global Matreshka, with the router and the form parser on it: Matreshka.initRouter, Matreshka.Router and Matreshka.parseForm. It works in the browsers jQuery 4 supports, Internet Explorer 11 included.
Without a bundler, matreshka.min.mjs is the same code as one ES module: every named export of matreshka, with initRouter, Router and parseForm included. It's one request, as small as the script-tag file.
After you've learned the most important API parts you can hardily start doing fantastic things. Classes, methods and properties marked with need to be learned primarily.
// store html binder in a short variableconst htmlBinder = Matreshka.binders.html;// create the class which inherits Matreshkaclass Application extends Matreshka { constructor() { super(); // bind a property x and the text field this.bindNode('x', '.my-input'); // bind the property x and the ".my-output" block this.bindNode('x', '.my-output', htmlBinder()); // if the property "x" has changed, // inform about it in the console this.on('change:x', () => console.log(`x is changed to "${this.x}"`)); }}const app = new Application();
3. That's it!
Now you can open the developer's console (by pressing F12) and write:
app.x = 'Hello World!';
Cool, isn't it? You can work with such magical properties directly. Run it live.
bindNode – Binds a property of an object to HTML node, implementing two-way data binding
bindOptionalNode – Works just the same as Matreshka#bindNode but it does not throw an exception if the node argument is an empty array, undefined or non-existent.
Binds a property of an object to HTML node, implementing two-way data binding
Matreshka#bindNode is the only method of the Matreshka class which is responsible for changing DOM (except array renderer). It creates a bridge between value of a property and state of HTML node on the page: from a simple input to a complicated widget (the complexity of elements is unlimited). After using this method, it isn't necessary to monitor the synchronizations between model and view.
Note that the method has static alternative, which works just the same but accepts any object as the first argument, shifting rest arguments to the right.
import { bindNode } from 'matreshka';const object = {};bindNode(object, key, node, binder, eventOptions);// instead of this.bindNode(key, node, binder, eventOptions);
The method acepts three arguments: a property name, HTML node and a binding rule (a binder). In its turn, a binder is an ordinary object and it can have the following properties: on, getValue, setValue, initialize, destroy (Read more here: binder). All the five properties are optional. It also allows to declare one-way data bindings (any direction).
The bindNode method supports the many-to-many bindings. Several elements can be bound to one property and several properties can be bound to one element, including ones from different instances of various classes.
For example, you want to bind a property of an object to a input[type="checkbox"] node:
this.bindNode('myKey', '.my-checkbox', { // when is element state changed? // - after 'click' event on: 'click', // how to extract element state? // - return 'checked' value getValue() { return this.checked; }, // how to set element state? // - set 'checked' value setValue(v) { this.checked = !!v; }});
After binding is declared, you can set value of an object property in your most habitual way and HTML node (in this case, a checkbox) will change its state immediately. After clicking on the checkbox, the property value will be changed to the corresponding one as well.
// sets checked = truethis.myKey = true;
More complicated example: binding object property to jQuery UI widget
<div class="my-slider"></div>
this.bindNode('myKey', '.my-slider', { // when is element state changed? // - after 'slide' event on: 'slide', // how to extract element state? // - return 'value' of the widget getValue() { return $(this).slider('option', 'value'); }, // how to set element state? // - set 'value' setValue(v) { $(this).slider('option', 'value', v); }, // how to initialize the widget? // you can initialize the slider in any way, // but 'initialize' function provides some syntactic sugar initialize() { $(this).slider({ min: 0, max: 100 }); }});
// will set the slider value 42this.myKey = 42;
It looks easy but you may ask a question: "What should I do to avoid writing these rules every time?". Indeed, there can be a lot of elements of the same type on the page: text fields, drop down menus, fields from the HTML5 specification as well as third party widgets (see the example above).
As observed in this documentation, the third argument is not obligatory for the ones of the bindNode method (see below). This problem is solved by the Matreshka.defaultBinders array which contains functions checking an HTML node against a set of rules and returns corresponding binder or undefined. You get an opportunity to reduce your code a great deal, putting binding rules into a separate part of your code and to use a syntax for binding without the third argument:
this.bindNode('myKey', '.my-element');
How to do it? You should add a function checking your element against a set of rules to the beginning of the Matreshka.defaultBinders array.
const checkboxBinder = () => { return { on: 'click', getValue() { return this.checked; }, setValue(v) { this.checked = !!v; } }};// the unshift method adds the function// to the beginning of the Matreshka.defaultBinders arrayMatreshka.defaultBinders.unshift(node => { // check if the element is a checkbox if(node.tagName === 'INPUT' && node.type === 'checkbox') { // if checking is OK, return a new binder return checkboxBinder(); }});
Matreshka.defaultBinders OOB has a support for all form elements without any exception: select (including multiple), textarea, output, input (including all types from the specification of HTML5: text, checkbox, radio, range, number, date, search, time, datetime, datetime-local, color and others). That means it is not necessary to designate a binder for standard elements.
Besides, after the binding, a new non-standard :bound(KEY) CSS selector is available for you.
this.bindNode('myKey', '.my-element');// will find the element '.my-inner-element' inside '.my-element'this.bindNode('myAnotherKey', ':bound(myKey) .my-inner-element');
And the syntax of possible event names is extended:
this.bindNode('myKey', '.my-element');// will handle the click on the '.my-element' elementthis.on('click::myKey', () => { ... });// will handle the click on the '.my-element .my-inner-element'this.on('click::myKey(.my-inner-element)', () => { ... });
If a node is not found Binding error: node is missing for key "KEY" error will be thrown. Check out Matreshka#bindOptionalNode.
Matreshka#bindNode can associate a class instance with the "main" HTML element on the page creating so-called sandbox. It is necessary to limit the instance influence on other HTML nodes. A special property sandbox is used for binding a sandbox.
<div class="my-sandbox"> <!-- your HTML code --></div>
this.bindNode('sandbox', '.my-sandbox');
The definition of the sandbox adds lots of conveniences for you. For example:
adds syntactic sugar for delegated DOM events in the Matreshka#on method
Keep in mind that you can bind only one sandbox element to sandbox property. You can try Matreshka#bindSandbox which does the same thing but removes previous binding.
// declare a sandboxthis.bindNode('sandbox', '.my-sandbox');// .my-element is being searched for in the sandboxthis.bindNode('myKey', ':sandbox .my-element');// it is not required to specify a key// for the delegated events inside a sandboxthis.on('click::(.my-button)', () => { ... });// will put the .inner-node element// which is inside the sandbox into the consoleconsole.log(this.$('.inner-node'));
The fourth argument of bindNode method is eventOptions. As usual this object can include special flags or custom data which will be passed to bind and bind:KEY event handlers.
If key string includes a dot then such string will be interpreted as a path to a property of nested object. Matreshka will listen all changes of given object tree.
this.a = { b: { c: 'foo' } };this.bindNode('a.b.c', node);this.a.b.c = 'bar'; // updates node by barconst oldB = this.a.b;this.a.b = { c: 'baz' }; // updates node by baz// node is not updated because// the connection with the object subtree is destroyedoldB.c = 'fuu';
In case if you need to use property name as is, use exactKey flag with true value.
When getValue is given then a state of an element will be extracted and assigned to bound property immediately after bindNode call in case if the property has undefined value. To force this behavior even if the property has non-undefined value use getValueOnbind flag with true value. To cancel this behavior use the same flag with false value.
When setValue is given then the value of the property will be set as element state immediately after bindNode call in case if the property has non-undefined value. To force this behavior even if the property is undefined use setValueOnBind flag with true value. To cancel this behavior use the same flag but with false value.
One of the most important feature of bindNode is that the logic of property change and the logic of element state change uses debounce pattern. It means that if bound property is changed many times in a short time then bound element state will be updated only once after small delay (thanks to debounceSetValue=true). If element state is changed many times in a short time (eg corresponding DOM event is triggered), the property gets new value only once after minimum delay (thanks to debounceGetValue=true).
As described above bindNode uses debounce pattern on property change and on bound node change. This doesn't apply to a moment when bindNode is called. To remind, when the method is called a property or a node is changed immediately. When debounceGetValueOnBind and/or debounceSetValueOnBind are set to true then debounce is turned on for binding initialization as well.
These flags allow to set debounce delay. debounceSetValueDelay is used when debounceSetValue or debounceSetValueOnBind is true, debounceGetValueDelay is used when debounceGetValue or debounceGetValueOnBind is true.
Even if you pass a binder to bindNode, the framework tries to find default binder at Matreshka.defaultBinder and extend it by properties of the passed object. This feature makes possible to use partially re-defined default binder.
For example, we want to bind input[type="text"] to a property. By default, the standard binder contains "on" property with "input" value for this kind of node. It means that the value of the instance property and node state will be synchronized when a user releases a key of the keyboard or pastes text from clipboard. In case if you want synchronization to be performed after the "blur" DOM event, you need to pass an object containing the only "on" property as the third argument. This object will extend the default binder, having retained getValue and setValue values.
this.bindNode('myKey', '.my-input', { on: 'blur' });
To cancel this behavior and use the binder as is, you can use useExactBinder flag with true value.
A binder containing the following properties: on , getValue, setValue, initialize, destroy. You can get more detailed information about binders in their documentation: see binder
To the Matreshka#bindNode method an object can be passed to avoid multiple invocation of the method and reduce code. Keys of the object are property names and values can get the following look:
A node
An object with properties node and binder
An array of objects with properties node and binder
If binder arg is passed as the second argument then it wil be used as the binder for those elements for which a binder wasn't specified.
this.bindNode({ foo: { node: ':sandbox .aaa', binder: Matreshka.binders.html() }, bar: '.bbb', baz: [{ node: '.ccc' }, { node: document.querySelector('.ddd'), binder: Matreshka.binders.prop('baz') }]}, { // will be used as a binder for .bbb and .ccc setValue(value) { foo(value); }});
Creates a dependency of one property value on values of others
calc creates a dependency of a property (target argument) on values of other properties (source argument). When source property is changed, target is re-calculated automatically.
Note that the method has static alternative, which works just the same but accepts any target object as the first argument, shifting rest arguments to the right.
import { calc } from 'matreshka';const object = {};calc(object, target, source, handler, eventOptions);// instead of this.calc(target, source, handler, eventOptions);
For reasons of code purity, the combination of strings and objects inside source array is not recommended. Instead, pass an object whose object property refers to source object. An example below makes the same job as shown at the previous example.
this.b = 1;this.c = 2;const someObject = { d: 3, e: 4};this.calc('a', [{ object: this, // the target object is "this" key: ['b', 'c']}, { object: someObject, key: ['d', 'e']}], (b, c, d, e) => b + c + d + e);console.log(this.a); // 10
The method is protected from circular references (for example, a depends on b, b depends on c and c depends on a) and if there is a calculation error, it does not block the page and does not throw an exception about the stack over-flow.
As you may noticed, arguments of handler function always follow the same order as source properties appear.
In case if you want to change a value of one source property and make it so that target property will not be recalculated, then use Matreshka#set method with skipCalc flag.
The fourth argument of calc method is eventOptions. As usual this object can include special flags or custom data which will be passed to change:TARGET event handler.
When a source changes with the silent flag, the target changes silently too. Custom data of the source change also reaches the target's handlers. The force, forceHTML, silentHTML and skipMediator flags of the source change don't apply to the target.
After calc is called, target property is calculated with no delays. But when source property is changed the debounce pattern is used. That means that target property will be changed in few milliseconds and only once even if source properties was changed many times in a short time.
this.b = 1;this.c = 2;this.d = 3;this.calc('a', ['b', 'c', 'd'], (b, c, d) => b + c + d);this.on('change:a', () => { // the handler will be called only once // despite that source properties was changed thrice console.log(`a is changed to ${this.a}`); // a is changed to 60});this.b = 10;this.c = 20;this.d = 30;console.log(this.a); // 6 instead of 60
To cancel debounce pattern when source properties are changed, in other words to make the calculation synchronously (as it was in previous versions of the method) pass debounceCalc with false value to the method.
this.b = 1;this.c = 2;this.d = 3;this.calc('a', ['b', 'c', 'd'], (b, c, d) => b + c + d, { debounceCalc: false});this.on('change:a', () => { // the handler will be called thrice // every time when b, c or d are changed // a is changed to... 15, 33, 60 console.log(`a is changed to ${this.a}`);});this.b = 10;this.c = 20;this.d = 30;console.log(this.a); // 60
As described above, target property is calculated immediately after the calc is called. To turn on debounce on calc call pass debounceCalcOnInit with true value to the method.
this.on('change:a', () => { // the handler will be called only once in a moment console.log(`a is changed to ${this.a}`); // a is changed to 6});this.b = 1;this.c = 2;this.d = 3;this.calc('a', ['b', 'c', 'd'], (b, c, d) => b + c + d, { debounceCalcOnInit: true});console.log(this.a); // undefined
In real world debounceCalcOnInit flag is unlikely to be useful. Just keep in mind that you can enable "total debounce" if needed.
It is known that target property gets new value after calc is called. To cancel this behavior and don't calculate a property immediately use setOnInit with false value.
this.calc('a', 'b', b => b * 2, { setOnInit: false});console.log(this.a); // undefined// but if this.b is changed the target property will be calculatedthis.b = 1;
As described above, it's possible to use a path to source property using a string that contains dots. In case if you need to use exact name of source property use exactKey with true value.
This flag allows to return Promise instance from the calculating function. Target property gets its value from resolved promise.
Warning! Promise cannot be canceled. Use the promiseCalc feature carefully and don't allow multiple calls of heavy functions.
If the sources change again before a promise resolves, only the latest calculation sets the target: the results of older ones are dropped.
this.calc('a', ['b', 'c'], (b, c) => { return new Promise(resolve => { setTimeout(() => { resolve(b + c) }, 1000); });}, { promiseCalc: true});this.b = 1;this.c = 2;// "a" will be changed in a second
this.calc('greeting', 'name', name => `Hello, ${name}!`);this.name = 'World';// ... in a momentalert(this.greeting); // 'Hello, World!'
The calculation of the rectangle perimeter with two sides known (and the calculation of the sides with the perimeter known)
this.a = 3;this.b = 4;this .calc('p', ['a', 'b'], (a, b) => (a + b) * 2) .calc('a', ['p', 'b'], (p, b) => p/2 - b) .calc('b', ['p', 'a'], (p, a) => p/2 - a);alert(this.p); // 14this.on('change:p', () => { // "The perimeter has been changed and equals 18" console.log(`The perimeter has been changed and equals ${this.p}`);});this.a = 5;
The method creates and fixes an instance of a class as given property value. When you try to override the property, instead of actual overriding, the instance is updated. Thus, we achieve integrity of an application, made on with Matreshka.js.
The method is an addon over Matreshka#mediate and it overrides a mediator.
Class instance is being created during the call of instantiate method. The current property value becomes the first argument of the class constructor. Provisions should be made so that either undefined (if a property hasn't contained any data before), or an object you should do something with (for example, to extend class instance by object properties) will get into the class constructor.
It looks easy in practice: you create an ordinary class which almost always receives some data to be handled (for example, to use it at Matreshka.Object#setData method).
While attempting to assign another value (an object or an array) to the property, the inner mechanism of instantiate method performs the following instead of the actual assignment:
If updateCallback function is given, the method calls it with two arguments: current property value and the data which code is trying to assign.
If updateCallback function isn't given and the class isn’t inherited from Matreshka.Object or Matreshka.Array, the instance is extended by object properties which is trying to be assigned.
A feature of this method is an absence of limitations on the class source. Any function-constructor that can be initialized using new operator and not only Matreshka's successors can act as a class.
A function which is called at every attempt of assigning new data to the property, allowing to customize logic of class instance updating with new data. The function receives two arguments: the current property value (class instance) and data which are attempted to assign.
class MyClass { // ...}// ...this.instantiate('x', MyClass);// trying to assign another value to x propertythis.x = { a: 42 };// this.x is still MyClass instancealert(this.x instanceof MyClass); // truealert(this.x.a); // 42
Getting a parent and property name. Besides data (the first argument), two arguments are passed to class constructor: a reference to an instance which has called instantiate and a name of a property.
class MyClass extends Matreshka { constructor(data, parent, key) { super(); // parent is MyParentClass instance // which is created x property // key equals to "x" }}class MyParentClass extends Matreshka { constructor() { super().instantiate('x', MyClass); }}
A non-standard way of using updateCallback for ignoring any changes of a property.
this.instantiate('x', MyClass, () => {});
In case if your class doesn't support the use of new operator, use Matreshka#mediate method instead of instantiate.
This method is used for transforming property value on its changing. For example, you want the property value to be always either of a certain type or an integer value, or to be no less than zero and no more than a hundred etc.
Note that the method has static alternative, which works just the same but accepts any target object as the first argument, shifting rest arguments to the right.
import { mediate } from 'matreshka';const object = {};mediate(object, key, mediator);// instead of this.mediate(key, mediator);
It deletes a handler which has been created before. All the three arguments are optional. You can delete both all the events (without passing any argument) and separate ones (having passed only the event name, the event name and the handler, the event name and the handler and the context).
Called without arguments, off removes every handler added with on, once and onDebounce and fires removeevent for each one. Bindings, calc dependencies and the events that Matreshka.Object and Matreshka.Array use internally stay.
The method adds an event handler for an instance of the Matreshka class. Refer to the complete list of possible events with the description here: eventNames.
Note that the method has static alternative, which works just the same but accepts any target object as the first argument, shifting rest arguments to the right.
import { on } from 'matreshka';const object = {};on(object, names, callback, triggerOnInit, context);// instead of this.on(names, callback, triggerOnInit, context);
Adding the same handler with the same context for the same event again has no effect. DOM events (click::x) follow the same rule.
Adds an event handler which is called only once during a definite period of time
The method allows to add an event handler to an instance of the Matreshka class, debouncing the handler. Callback function can be called only once during a definite period of time. As to the rest the method works the same as Matreshka#on.
Parses DOM tree, declaring property bindings on which are double braced.
Matreshka includes a simple DOM parser that handles double braced syntactic constructions. parseBindings method receives HTML string, DOM node or selector corresponding to DOM node as the first argument.
As the method is DOM template engine (and not HTML-replace parser), all child DOM nodes of the passed element remain in their same state (for example, DOM events aren’t erased).
<!--will create text node in place of {{user.name}}and will bind name property from user object to this nodeJS: this.user = {name: 'Joe'}--><span>Hello, {{user.name}}</span>
Binding form elements.
<!--will bind "x" instance property to a text field (two-way data binding)JS: this.x = 'some value';--><input type="text" value="{{x}}"><!--For binding textarea and select you should use value attribute--><textarea value="{{x}}"></textarea><select value="{{x}}">...</select><!--will bind "x" instance property to a checkbox (two-way data binding)JS: this.x = true;--><input type="checkbox" checked="{{x}}">
Attributes binding.
<!--href attribute value will depend on "category"and "someObject.page" value (one-way data binding)JS: this.category = 'matreshka'; this.someObject = { page: 42 };--><a href="http://example.com/{{category}}/{{someObject.page}}">A link</a><!--The result:<a href="http://example.com/matreshka/42">A link</a>-->
In case if you develop a large form with standard HTML5 fields, the method will help you save time on declaring numerous bindings. Besides, parseBindings is useful in case of creating a very simple collection which doesn’t require implementation of a complicated model.
Returns:$nodes – A collection of DOM nodes, which is passed to the method as an argument.
this.bindNode('sandbox', '.app');this.select('.my-element');// the same asthis.nodes.sandbox.querySelector('.my-element');// the same as$('.app').find('.my-element')[0];
this.bindNode('sandbox', '.app');nodes = this.selectAll('.my-element');// the same asnodes = this.$('.my-element'); // $ is a short reference to selectAll// the same asnodes = $('.app').find('.my-element');
The :bound(KEY) selector
this.bindNode('myKey', '.my-element');nodes = this.selectAll(':bound(myKey) .my-another-element');// the same asnodes = $('.my-element').find('.my-another-element');
Sets a property value allowing to pass event options object as the third argument
The list of the supported flags:
silent - do not call the change and change:KEY events
silentHTML - do not change states of bound HTML nodes
force - call the change and change:KEY events even though the property value has not been changed
forceHTML - change a state of bound element even though the property value has not been changed. This option is usable if the bound element has been rendered after the binding (for example, some option tags have been added to select tag)
skipMediator - prevents the property transformation by a mediator (see Matreshka#mediate)
skipCalc - prevents the work of dependencies created with Matreshka#calc
Destroys a binding between given property and HTML node
Using this method you can delete the binding between a property and HTML node, which has been added recently and no longer needed.
A key with dots is a path to a nested property, as in Matreshka#bindNode; with the exactKey: true event option it is used as is. null as the key also removes the bindings of nested properties ("a.b").
this.bindNode('myKey', '.my-element');// changes the property value and the state of the HTML elementthis.myKey = true;this.unbindNode('myKey', '.my-element');// only the property value is being changed nowthis.myKey = false;
The variation makes possible to pass an array which includes objects with the following properties:
key - a property name
node - a node bound to key (optional)
This variation is useful because it matches one variation of Matreshka#bindNode method, allowing to store bindings in a variable to easily remove them when needed.
The sandbox key is reserved for the binding: it is left out of Object.keys and JSON.stringify, and reading or assigning this.sandbox throws an error. The bound node is this.nodes.sandbox.
The object contains bound elements in the form of separate DOM nodes for quick access
Pay attention, every object property has got the first node of the bound ones to the corresponding property. Use Matreshka#$nodes for getting all the nodes bound to a certain property.
The function accepts any object and returns an instance of externally inaccessible class which adopts universal methods allowing them to be called in a chain to change given object.
An implementation of classes based on the prototype inheritance
The Class function allows to use the classic OOP when ECMAScript 2015 classes cannot be used somehow.
If prototype has no own constructor property, the class calls the parent constructor with the same arguments, like an ECMAScript 2015 class without a constructor. An ECMAScript 2015 class can be passed as constructor: it runs on instantiation, but the methods declared in its body are not inherited; put them in prototype.
Returns:class – class (a class constructor to be exact)
const A = Matreshka.Class({ method1() { ... }});const B = Matreshka.Class({ // B is inherited from A extends: A, method2() { ... }});const C = Matreshka.Class({ // С is inherited from B extends: B, method2() { // calling the parent method B.prototype.method2.apply(this, arguments); }, method3(a, b) { ... }});const D = Matreshka.Class({ // D is inherited from C extends: C, method3(a, b) { // calling the parent method C.prototype.method3.apply(this, arguments); }});
Passing an object with static methods and properties
Turns on two-way data binding between properties and parts of the URL
The router is hash-based by default: it uses location.hash with a hashbang (#!/a/b/). Pass "history" as the third argument to use the path (/a/b/) through the History API instead.
// location.hash is used thereinitRouter(object, '/a/b/c/');object.a = 'foo';object.b = 'bar';object.c = 'baz';// makes location.hash to be #!/foo/bar/baz/
If you need to use History API instead of hash, pass "history" as the third argument.
initRouter(object, '/a/b/c/', 'history');
How does "traditional" routing work? A developer defines a rule (route) and defines a function which will be called when current path fits given rule.
route("books/:id", id => { // do something});
The principle of initRouter is different. You define which part of URL (both hash, and HTML5 History are supported) need to be synchronized with given property.
Let's say you need to synchronize "x" with the first part of location.hash and "y" with the second.
initRouter(object, '/x/y/');
Now when you type...
object.x = 'foo';object.y = 'bar';
...location.hash is automatically changed to #!/foo/bar/
And vice versa. When the URL is changed manually or via back and forward buttons, the properties will be changed automatically.
location.hash = '#!/baz/qux/';// ... after a momentconsole.log(object.x, object.y); // 'baz', 'qux'
As usually you can listen property changes with Matreshka#on method.
Matreshka.on(object, 'change:x', handler);// for Matreshka instances: this.on('change:x', handler);
Values are encoded in the URL and decoded back: object.x = 'a b/c' gives #!/a%20b%2Fc/, and object.x stays 'a b/c'. A hash which doesn't start with #! (an anchor such as #top) is not a route.
1. If a property has a value (not undefined, null or '') then URL will be changed immediately after initRouter call. A property without a value gets its value from the URL.
object.x = 'foo';initRouter(object, '/x/y/');
2. If a property gets null, undefined or '' then all next listed properties will get null as new value.
initRouter(object, '/x/y/z/u/');object.y = null; // makes object.z and object.u to be null as well
The idea is to get actual state of URL. It could be weird to get "z" with value "foo" in case of non-existing bound part of URL.
The router supports HTML5 History as well. To initialize it you need to pass optional argument type with "history" value to the initRouter function (by default type is "hash").
initRouter(object, '/x/y/z/', 'history');
The router reads and writes location.pathname; the query string and the hash stay as they are.
In a page with the script tag bundle the function is Matreshka.initRouter.
const element = document.createElement('input');element.type = 'text';console.log(Matreshka.lookForBinder(element));// will return something similar to the following object{ on: 'input', getValue() { return this.value; }, setValue(v) { this.value = v; }}
Only arrays and Matreshka.Array instances become Matreshka.Array; every other object, even one with a length property, becomes Matreshka.Object. A Matreshka.Object passed in gives only its data keys.
Returns:matreshka – a newly created instance of Matreshka
An array of functions which return a corresponding binder
defaultBinders is the array of functions which check an element in turn against given rules in these functions and return a binder (see binder). This array is used when the third argument has not been passed to the Matreshka#bindNode method. See more detailed information about bindings in Matreshka#bindNode documentation.
Matreshka.defaultBinders.unshift(element => { // check if the element has "foo" class name if(element.classList.contains('foo')) { // if checking is OK, return a new binder return { on: ..., getValue: ..., setValue: ... }; }});// ...this.bindNode('myKey', '.foo.bar');
parserBrackets object allows to change default syntax of the parser. It contains two properties: left (left bracket, "{{" by default) and right (right bracket, "}}" by default)
Matreshka.Object is a class which is responsible for key-value data. Its goal is to separate "service" properties from data that can be passed to a server or kept in a local storage. The class is inherited from the Matreshka class and includes all its properties and methods.
Imagine you create an object which includes "a", "b" and "c" properties. Let's assume that "a" and "b" are the properties which must be sent to a server, and "c" property is just responsible for some application state (for example, it contains the sum of "a" and "b"). The server does not need the "c" property. So we have to separate the properties which are responsible for data from ones which are not.
If you don't know which properties are specified in advance, you can always use the Matreshka.Object#setData method, which declares not only properties responsible for data but sets their values at once.
this.setData({ a: 1, b: 2});this.c = 3;
After an application has found out what is data, Matreshka.Object instance can be converted into an ordinary object by the Matreshka.Object#toJSON method and passed to a server or kept in a local DB (for example, in localStorage).
// will return an object { a: 1, b: 2 }this.toJSON();
On add or change of data properties set and modify events are fired. On remove of data properties remove and modify events are fired. That means you can listen any changes of Matreshka.Object instance with the only modify event name.
this.on('modify', () => { alert('an object is modified');});
keyOf – Searches for specified property value among others which are responsible for data and returns one key if this value has been found (very similar to Array.prototype.indexOf function)
keys – Returns an array of property names which are responsible for data
removeDataKeys – Deletes given property names from a list of property names which are responsible for data (but does not delete the properties)
setData – Sets a property and adds property name to a list of property names which are responsible for data
toJSON – Converts an instance and its internal properties into an ordinary object
values – Returns an array of property values which are responsible for data
Searches for specified property value among others which are responsible for data and returns one key if this value has been found (very similar to Array.prototype.indexOf function)
this.setData('a', 1).setData('b', 2);// assign 3 to the 'c' property,// but do not add the key to a list of keys which are responsible for datathis.set('c', 3);this.each((value, key) => { console.log(key, value);});// displays 'a' 1 and 'b' 2console.log(this.keys()); // displays ['a', 'b']console.log(this.toJSON()); // displays { a: 1, b: 2 }
After using the Matreshka.Object#setData method, you can work with a property like with an ordinary one
Converts an instance and its internal properties into an ordinary object
The method works recursively, calling toJSON for all internal properties which have such method. To cancel this behavior pass false as the only argument.
The Matreshka.Array serves as collection class in Matreshka framework. It is inherited from the Matreshka class, obtaining all parent possibilities without exception. Besides, Matreshka.Array has all methods that ordinary array has.
A programmer familiar to the methods of native Array can understand immediately by means of which method adds (push, unshift, splice), deletes (pop, shift, splice), sorts (sort, reverse) items etc.
For the reason that methods work the same as original ones (with a few exceptions), they are not presented in this documentation separately but they are gathered in the Matreshka.Array#METHOD section.
The method_ syntax is used for this, where underscore at the end of a method name means that the last argument is an event object. Such methods are not given in this documentation because it is necessary to remember their syntax only. See Matreshka.Array#METHOD_.
While using a methods adopted from built-in Array, events with corresponding name are fired. Calling the push method, the push event is fired, calling the shift method, the shift event is fired, calling the sort method, the sort event is fired, and so on.
this.on('push', evt => { console.log('push is called');});this.push(1, 2, 3);
While adding items, add and addone events are fired. The first one is fired once on adding (for example, you have added few items using push and the event has been fired only once), the second one is fired once on every added item. On the add event triggering, an array of added items is passed to an event object as added property and on the addone triggering, each particular added item is passed to it as addedItem property.
// the handler will be called three times,// as three new item have been added to the arraythis.on('addone', evt => { console.log(evt.addedItem); // 1 ... 2 ... 3});this.push(1, 2, 3);
On removing items the same logic is observed: remove triggers once even though several items have been removed (removed items are contained in the removed property) and the removeone event triggers for each removed item individually (removed item is contained in the removedItem property).
this.push(1, 2, 3, 4, 5);// the handler will be called three times,// as three items have been removed from the arraythis.on('removeone', evt => { console.log(evt.removedItem); // 2 ... 3 ... 4});this.splice(1, 3);
On every modification of an array the modify event is fired, allowing to catch all changes in the array (adding, removing, re-sorting).
length is an ordinary property which can be bound to HTML node or you can listen changes using the change:length event name.
For example, on adding three items using the push method with three arguments, the following events: push, add, addone (three times), modify, change:length are fired.
The Matreshka.Array#Model property specifies a class of items that an array contains. It is recommended to inherit Model from the Matreshka.Object class or the Matreshka.Array one (in case if it is necessary to get a collection of collections) in order to get the opportunity of converting an array into an ordinary one recursively by using the Matreshka.Array#toJSON method.
Matreshka.Array can render HTML nodes on a page automatically in any modifications of an array. The Matreshka.Array#itemRenderer property is used for that. You do not have to worry about rebuilding the HTML tree, Matreshka.Array does it for you. For detailed information read the documentation of Matreshka.Array#itemRenderer.
Any method from Array.prototype with the possibility of passing event object
Having found out more about Matreshka.Array#METHOD, it becomes clear that the methods do not support an event object passing as they exactly duplicate the syntax and the number of arguments of the built-in Array. The METHOD_ syntax allows to pass some data to event handlers.
The property defines a class of items which will be inserted to a collection
Every time items are added to an array, the built-in handler checks if added item is Model instance and converts it into the one if the check fails. It is recommended to inherit Model from the Matreshka.Object or Matreshka.Array class (in case if it is necessary to get a collection of collections) to get an opportunity of an array conversion into ordinary one by Matreshka.Array#toJSON method.
Use Matreshka.Array#mediateItem for more flexible control of an item class (for example, if you need to use one class for certain items and another one - for others).
Model can be declared as a class field (Model = MyModel;) as well as a getter. Class fields are set after super(...) returns, so the items passed to super(...) are converted when a method next changes the array; a get Model() getter converts them right away.
Changing Model later converts the items the array already has and replaces their rendered nodes.
This method works almost like orderBy from lodash. It accepts a key or a list of keys as the first arg and an order (asc/desc) or a list of orders as the second arg.
The method allows to convert any array or array-like into the Matreshka.Array instance. If nothing has been passed as the first argument, the instance is cleansed.
If selector arg isn't passed then the collection will be restored from child nodes that placed in a container ("container" or "sandbox").
The method fires "render" event and calls onRender and onItemRender functions (look at the docs) for every newly added item similar to usual rendering.
Rerenders DOM nodes of items which are included into an instance
This method renders array items in an array container. If a node which is associated to an array item has already been created, the method reinserts it into container of the array instead of rerendering it all over again.
The method can be useful in case when items have been added to the array before declaring a sandbox or a container.
To force items rerender (e. g. you use custom template engine) pass a property forceRerender with true value to an event object.
HTML string, a selector or a function which is responsible for rendering DOM nodes of an array on a page
The itemRenderer overridable property allows to render corresponded HTML nodes of items of an array without a programmer's participation. On a new item insertion into an array, HTML node is created automatically. This node becomes a sandbox (see. Matreshka#bindNode) (this behavior can be canceled, read below) for inserted item and it is inserted into HTML container which is defined in an array.
For brevity, the "class fields" syntax will be used in examples at this article.
itemRenderer and Model work as class fields as well as getters; assigning a new value to an itemRenderer class field rerenders the items. See Matreshka.Array#Model about the items passed to super(...).
In order to define a place where rendered HTML nodes will be inserted, it is necessary to define a container. HTML sandbox should be declared for an array or a special container key should be bound to the HTML container for that. Read more detailed information about bindings and sandboxes in Matreshka#bindNode.
Now all newly created <li> nodes will get into the .my-list node.
If you do not want to insert HTML nodes straight into the sandbox, you can bind container property to needed HTML node. This logic is required in case if a sandbox is not limited by collection items and it includes other HTML nodes.
<div class="my-widget"> <h1>This is my awesome list</h1> <ul class="my-list"></ul></div>
class MyArray extends Matreshka.Array { itemRenderer = '<li>'; get Model() { return MyModel; } constructor() { super(); // sandbox definition this.bindNode('sandbox', '.my-widget'); // a definition of container for HTML nodes this.bindNode('container', '.my-list'); }}
In the example above the HTML nodes will be inserted into .my-list instead of .my-widget.
The itemRenderer property supports a few variants of defining, but they all must contain or return the only HTML node.
In case if you carry over the templates for the items to the HTML page, itemRenderer supports the selector as a value. When this occurs, Matreshka.Array will search for HTML node in DOM tree and it will extract innerHTML of found node. In case if a node is not found, an exception will be thrown.
HTML string is different from a selector due to the presence of the < symbol in a string.
The usage of a function as the itemRenderer property value gives an additional code flexibility if it is necessary to dynamically generate HTML node for rendering. A function can return:
Sometimes it is convenient to declare a renderer inside a model class. The renderer property overlaps the itemRenderer value if it is specified for a child item of a collection.
In this case you do not have to designate itemRenderer at all because render of a child item adopts all its roles. The syntax remains the same: HTML string, a selector or a function can be used.
After an item has been inserted into an array and its HTML node has already been created but it hasn't been inserted into array container yet, the render event is fired on inserted item. After its triggering you can declare needed data bindings.
afterrender is fired when HTML node is inserted into the container.
The code above will create the following HTML tree:
<form class="my-form"> <label> <input type="checkbox" class="my-checkbox"> <span class="text">Buy a raccoon</span> </label> <label> <input type="checkbox" class="my-checkbox"> <span class="text">Sell the raccoon</span> </label></form>
And it will bind the checkboxes to the corresponding isChecked and text properties.
Remember, the opportunity of listening delegated events is implemented in the framework. The array can listen to an event of an item rendering, using the *@render event name (see the documentation of eventNames).
this.on('*@render', () => { alert('Child item is rendered');});
Rendered HTML node becomes a sandbox for inserted item allowing to use the :sandbox selector and some other possibilities after rendering. If an item enters a few collections at once, set the bindRenderedAsSandbox property to false for an item to cancel this behavior.
class MyModel extends Matreshka.Object { bindRenderedAsSandbox = false; // ...}
To improve the readability of code there is a virtual method called Matreshka.Array#onItemRender, which can be used instead of render event. As second alternative, the onRender can be used for a "model".
If you have a look at the examples of using Matreshka.Array and Matreshka.Array#itemRenderer, you can notice that all logic which is responsible for the two-way and one-way data binding is contained in JavaScript code. But when you develop a very simple collection which does not include complicated logic, lots of bindings, etc, you would like to have a shorter variant of the binding declaration. A template including bindings (see Matreshka#parseBindings) can be passed to itemRenderer for that.
class MyArray extends Matreshka.Array { itemRenderer = `<label> <input type="checkbox" checked="{{isChecked}}">{{text}} </label>`; // ...}const app = new MyArray();
As is seen from above if the render property of the child item is specified, Matreshka.Array will try to render it. In order to completely cancel rendering for an array, set a property renderIfPossible of Matreshka.Array instance as false.
class MyArray extends Matreshka.Array { renderIfPossible = false; // ...}
By default, when you add an object to an array the framework will try to render it using itemRenderer. It gives a great advantage in cases when you have two or more lists which include the same object. The lists react instantly on any change in the object.
But sometimes you just need to move an object across few collections without re-rendering it again. If you need to move object to another collection including its sandbox use the moveSandbox flag while adding the new item to another array.
It's not obligatory to fill an array with only Matreshka instances, you can render any kind of object. Bindings for such objects can be defined using static method Matreshka.bindNode.
class MyArray extends Matreshka.Array { // Model is not given itemRenderer = ...; onItemRender(item) { Matreshka.bindNode(item, 'x', ':sandbox .some-node'); }}
One more little example: the rendering of a simple list:
trackBy property indicates a key of unique IDs for collection items
In case if a client and a server activelly communicate with each other and collection items have unique IDs, then redrawing entire collection from scratch does not make sense. After the server respond with new collection, much better to check does the old collection contain objects which have the corresponding identifiers. If object ID from new collection matches object ID from old one, old object will be updated and used again. That means a new object (new instance of Matreshka.Array#Model) will not be created and new DOM node will not be rendered.
trackBy works only using Matreshka.Array#recreate because recreate is the only method which recreates collection from scratch.
In examples below _id key is used as identifier (you can use any other key).
class MyArray extends Matreshka.Array { get trackBy() { return '_id'; } constructor() { super(); //... }}const arr = new MyArray();// adds 3 objects to the collectionarr.recreate([ {_id: 0, name: 'Foo'}, {_id: 1, name: 'Bar'}, {_id: 2, name: 'Baz'}]);// the next recreate call// removes an object with _id: 0// adds an object with _id: 3// updates an object with _id: 1 (changes name from Bar to BarNew)// updates an object with _id: 2 (changes name from Baz to BazNew)// resorts collectionarr.recreate([ {_id: 1, name: 'BarNew'}, {_id: 3, name: 'Qux'}, {_id: 2, name: 'BazNew'}]);
trackBy can have "$index" value, allowing to update objects by their index in collection.
class MyArray extends Matreshka.Array { get trackBy() { return '$index'; } constructor() { super(); //... }}const arr = new MyArray();// adds 3 objects to the collectionarr.recreate([ {name: 'Foo'}, {name: 'Bar'}, {name: 'Baz'}]);// the next recreate call// updates all 3 items with new "name"// adds an object with name "Qux"arr.recreate([ {name: 'NewFoo'}, {name: 'NewBar'}, {name: 'NewBaz'}, {name: 'Qux'}]);
A namespace for binders. Out of the box it contains general-purpose binders and can be extended by you so as not to make a mess of the global namespace.
Take a little agreement into consideration: every property from the Matreshka.binders namespace must be made as a function which returns a binder (such functions usually called "binder creators").
At this documentation the properties from Matreshka.binders are used directly. But to make your code more readable it's recommended to assign them to a variable.
const html = Matreshka.binders.html;// ...this.bindNode('x', node, html());
Or import them as CJS/ES2015 module:
// import few binders per onceimport { binders } from 'matreshka';const { html, text, prop } = binders;
attr – Returns a binder which changes an attribute of DOM node depending on an object property value
className – Returns a binder which switches over DOM node class name depending on an object property value. If property value equals true non-strictly, a class name is added, otherwise - it's removed. The logic can be changed by passing false as the second argument and in this way, a class name will be added when a property value equals false non-strictly and vice versa.
dataset – Returns a binder which changes given dataset property of bound DOM node depending on an object property value.
display – Returns a binder which controls a visibility of DOM node (using style.display) depending on an object property value
existence – Returns a binder which controls an existence of DOM node at DOM tree depending on an object property value
html – Returns a binder which changes innerHTML of bound DOM node depending on an object property value
input – Returns a binder which binds an object property to an input element value. It is not obligatory to use the binder directly because it is included in the Matreshka.defaultBinders list.
output – Returns a binder which binds an object property to an output element value. It is not obligatory to use the binder directly because it is included in the Matreshka.defaultBinders list.
progress – Returns a binder which binds an object property to a progress element value. It is not obligatory to use the binder directly because it is included in the Matreshka.defaultBinders list.
prop – Returns a binder which changes given property of DOM node depending on an object property value
select – Returns a binder which binds an object property to a select element value. It is not obligatory to use the binder directly because it is included in the Matreshka.defaultBinders list.
style – Returns a binder which changes given style property of bound DOM node depending on an object property value
text – Returns a binder which changes textContent of bound DOM node depending on an object property value
textarea – Returns a binder which binds an object property to a textarea element value. It is not obligatory to use the binder directly because it is included in the Matreshka.defaultBinders list.
this.bindNode('myKey', '.my-node', Matreshka.binders.attr('foo', value => `Hello, ${value}`));this.myKey = 'World'; // the foo attr now has value "Hello, World"
Returns a binder which switches over DOM node class name depending on an object property value. If property value equals true non-strictly, a class name is added, otherwise - it's removed. The logic can be changed by passing false as the second argument and in this way, a class name will be added when a property value equals false non-strictly and vice versa.
this.bindNode('myKey', '.my-element', Matreshka.binders.dataset('myProp', value => `Hello, ${value}`));this.myKey = 'foo'; // the attr data-my-prop now has value "Hello, foo"
import { binders } from 'matreshka';const { existence } = binders;
Matreshka.binders.existence([bool=true]) → binder
Returns a binder which controls an existence of DOM node at DOM tree depending on an object property value
The binder works the same way as Matreshka.binders.display, but instead of visibility change the existence at page DOM is changed. The binder is useful for:
Big appications: show one or another page depending on route state;
For infinite scrolling;
For other cases where you need to hide an element but its existence at DOM tree isn't necessary.
this.bindNode('disabled', '.my-button', Matreshka.binders.prop('disabled'));// sets disabled = true property for the nodethis.disabled = true;// sets disabled = false property for the nodethis.disabled = false;
The usage of mapping function
this.bindNode('myProp', '.my-node', Matreshka.binders.prop('foo', value => `Hello, ${value}`));// foo property of the element now has value "Hello, World"this.myProp = 'World';
this.bindNode('myKey', '.my-element', Matreshka.binders.style('backgroundColor'));this.myKey = 'red'; // background-color of .my-element is red now
The usage of mapping function
this.bindNode('myKey', '.my-element', Matreshka.binders.style('backgroundImage', value => `url("${value}")`));this.myKey = 'cats.jpg'; // backgroundImage now equals to "url("cats.jpg")"
Returns a binder which binds an object property to an input element value. It is not obligatory to use the binder directly because it is included in the Matreshka.defaultBinders list.
For text-like inputs, undefined and null show as an empty string. For a radio input, a checked radio sets the property to its value; an unchecked radio doesn't change the property.
Returns a binder which binds an object property to an output element value. It is not obligatory to use the binder directly because it is included in the Matreshka.defaultBinders list.
Returns a binder which binds an object property to a progress element value. It is not obligatory to use the binder directly because it is included in the Matreshka.defaultBinders list.
Returns a binder which binds an object property to a select element value. It is not obligatory to use the binder directly because it is included in the Matreshka.defaultBinders list.
undefined and null select the option without a value, if there is one. With multiple set to true, the property can be an array of values, a single value or null (nothing selected); values are compared as strings, so numbers work too.
Returns a binder which binds an object property to a textarea element value. It is not obligatory to use the binder directly because it is included in the Matreshka.defaultBinders list.
Matreshka.initRouter is powered by Matreshka.Router class. It accepts only one argument - router type ("hash", "history" or a custom string).
By default, the library creates two instances of Matreshka.Router with types hash and history. They live at Matreshka.Router.hash and Matreshka.Router.history. The router uses lazy initialization so when you just attach the script onto webpage, the library does nothing.
For these two types of instances the singleton pattern is used. That means when you're trying to create another instance of hash routing via new Matreshka.Router('hash'), the Matreshka.Router.hash will be returned instead of new instance creation. This logic centralizes URL handling, gives positive effect to the performance and doesn't make potential collisions. Objects which are handled by initRouter just subscribe to the changes of needed type of the router.
Custom instances (non-hash and non-history) of Matreshka.Router can be created manually in case if you generate URL for further use. At this case changes of target properties don't affect on hash and don't call pushState.
subscribe(object, route) - subscribes object for route changes.
init() - used for lazy initialization on first use of Matreshka.Router.hash or Matreshka.Router.history and in the subscribe method (no need to call it manually).
binder contains all information about how to synchronize instance property value with DOM node state. Every member of a binder uses HTML node as its context (this)
DOM event (or space-delimited list of events) which tells when the node state is changed. Besides, it accepts a function as a value if you need to customize a listener definition
// for any eventthis.on('addevent', evt => {...});// for "someevent" eventthis.on('addevent:someevent', evt => {...});// the line below fires "addevent" and "addevent:someevent"this.on('someevent', evt => {...});
// for any eventthis.on('removeevent', evt => {...});// for "someevent" eventthis.on('removeevent:someevent', evt => {...});// the line below fires "removeevent" and "removeevent:someevent"this.off('someevent', evt => {...});
If you need to listen an event of every item of Matreshka.Array or every data property of Matreshka.Object, you can use an asterisk "*" instead of specific property name.
For the app pre-rendering Matreshka.js can be used on Node.js (window global object can be created via jsdom) or any template system you want on any server platform. The first case is fine for static HTML generation and the second for dynamic pages.
The task of client-side is to restore application state from HTML. Matreshka#bindNode extracts element value and assigns it to a property and Matreshka.Array#restore restores a state of a collection.
At this page you often can see the phrase "micropattern debounce". This is widely used pattern which enforces that a function not be called again until a certain amount of time has passed without it being called. More info can be found there.
An application written with Matreshka.js usually represents one nested JavaScript object where every branch is Matreshka instance. The new branches are created using Matreshka#instantiate which ensures the integrity of the application and allows to replace a state of the application using ordinary assignment.
The first thing: you need to set bindRenderedAsSandbox as false for an item class. It turns off automatic sandbox initialization for rendered object (two sandboxes for one object aren't allowed).
The second thing: when render event is fired, check where the object is rendered. Parent array can be get using parentArray property of the event object.
Example. You have User class and two collections UsersA and UsersB (their Matreshka.Array#itemRenderer can be different). For both collections User is a model.
Actually there are many ways to solve this problem. For example bindings can be declared at classes of the collections (an array will listen to render event of inserted objects)...