How "snippets" can help in web development with Malina.js





Nobody asks why functions are needed, because this is an obvious and useful thing in programming. Functions allow you to reuse your code and make your application architecture better.



Why not use the same ability in component templates. Many frameworks nowadays allow components to be used inside other components. But this is more like connecting a module than just functions. After all, a component, in addition to a template, can have its own JavaScript code, its own styles, and it is very isolated (which is good).



For this case, Malina.js has, as it were, “functions” for the “fragment” templates , they allow you to reuse different fragments of the template, they are much lighter than components, they do not need to be moved to a separate file (which is often necessary with components), and they have some features that ordinary functions have, for example recursion and closures, because the fragment as a result is compiled into an ordinary function.



1. Reuse of a fragment of a template



When you are working on a component template, especially if it is a form, input elements, panels, etc., you may have duplicate blocks that could be reused. Below is a piece of the template from js-framework-benchmark , in which there are a number of identical buttons:







Using "fragment" it might look like this:







Here a fragment buttonwith two arguments is declared id, name, and a "click" event is sent from the button @click. This row of buttons could be made using a directive for/each, but a fragment can be used not only in one line.



2. Closures



Because a fragment is compiled into a function, which means it can be declared almost anywhere, even inside a loop for/each, so it can use closures. In the example below, the snippet boxhas an argument text, a closed loop variable color, and a reference to a function clickfrom the root of the component that is called on click:@click={click(text, color)}







3. Recursion



"Fragment" can call itself which allows to do recursion and build trees, also "fragment" can be located in the bottom of the component, because in JavaScript, the function is available throughout the (current) scope, even if it is declared at the end.



Below is an example of a snippet drawthat calls itself and builds a tree:







Conclusion



A "fragment" is a lightweight "piece" of template that can be reused within a component, it helps to make the component more compact with better structure.



All examples can be tried in the online REPL editor , examples in the gist .



Thank you for attention.



All Articles