1 | <page title="XJS user manual 666">
|
2 | <x-md>
|
3 | # XJS against all the boilerplate!
|
4 | The Javascript for a module is usually stored in a `module.js` file. But because writing some sort of code can be fastidious, toloframework can use a `module.xjs` file to generate Javascript before minification. XJS files are written in a syntax near the JSON one: it is just less restrictive on how you use strings and it allows you to put Javascript comments.
|
5 |
|
6 | XJS is extensible and you can easily add your own code generators.
|
7 | For now, we will focus on the builtin generator: __View__.
|
8 |
|
9 | ## XJS View
|
10 | Writing good code for visual components with data binding can result in lot of unreadable javascript code. View helps you writing such a code in a declarative way. Let's take an example:
|
11 |
|
12 | <x-widget name="tfw.view.checkbox" $content="Hello world!" $value="true"/>
|
13 |
|
14 | To create this checkbox component, all you need is a `jsx` file and a `css` file. And you can click on it: it really works! And when it has the focus, you can use the keyboard to toggle its state. And all this without a single line of javascript code.
|
15 |
|
16 | <x-code lang="xjs">// tfw.view.checkbox
|
17 | {View BUTTON
|
18 | view.attribs: {
|
19 | value: false,
|
20 | reversed: false,
|
21 | content: Checkbox
|
22 | }
|
23 | class:tfw-view-checkbox
|
24 | class.ok:{Attrib value}
|
25 | event.tap:{Toggle value}
|
26 | event.keyup:{Toggle value}
|
27 | [
|
28 | {DIV class:pin [
|
29 | {DIV class:"bar thm-ele2"
|
30 | class.thm-bgSL|thm-bg2: {Attrib value} }
|
31 | {DIV class:"btn thm-ele2"
|
32 | class.thm-bgS|thm-bg1: {Attrib value} }
|
33 | ]}
|
34 | {DIV class:txt {Attrib content}}
|
35 | ]
|
36 | }</x-code>
|
37 | To understand this syntax you must know that permissive JSON uses implicit attribute names. So stuff like `{Attrib value}` can be translated in pure JSON as `{"0": "Attrib", "1": "value"}`.
|
38 |
|
39 | Basically, XJS takes an object and generate javascript code. To know which code generator to use, it looks at the attribute "0" of the object. In our case, this is __View__.
|
40 |
|
41 | A view is an HTML element which can contain other HTML elements or views. When the first implicit attribute is uppercase, this is an HTML element, otherwise this is a View. As you can see here, this view is a BUTTON. The module `tfw.view.checkbox` will be a class which you can instantiate and use like this:
|
42 | <x-code>var Checkbox = require("tfw.view.checkbox");
|
43 | var chk = new Checkbox({ content: "Hello world!" });
|
44 | document.body.appendChild( chk.$ );
|
45 | </x-code>
|
46 |
|
47 | All views have the `$` attribute which maps to the root HTML element.
|
48 | Other attributes can be defined with their default values in the XJS object:
|
49 | <x-code lang="xjs">view.attribs: {
|
50 | value: false,
|
51 | reversed: false,
|
52 | content: Checkbox
|
53 | }</x-code>
|
54 |
|
55 |
|
56 |
|
57 | </x-md>
|
58 | </page>
|