v2.0.3

Directive Parsing

Last updated


The order in which RJS's #SET_DOM applies directives while walking a template, and what each directive (:path, :for, :if, :model, :[attr], @[event]) does.

Directive Parsing Order


#SET_DOM walks each child element and applies directives in a fixed order. :path- and :for-tagged nodes short-circuit into their own handlers and skip the rest of the pipeline for that node:
graph TB
    Node["child element"] --> PathCheck{":path attr?"}
    PathCheck -->|yes| SetPath["#setPath: fetch fragment, inline it, return"]
    PathCheck -->|no| ForCheck{":for attr?"}
    ForCheck -->|yes| FitFor["#FIT_FOR: expand loop, return"]
    ForCheck -->|no| SetIf["#setIf: :if / :else-if / :else"]
    SetIf --> FitModel["#FIT_MODEL: two-way form binding"]
    FitModel --> FitAttr["#FIT_ATTRIBUTE: :[attr] / :[css]"]
    FitAttr --> FitEvent["#FIT_EVENT: @[event]"]
    FitEvent --> FitText["#FIT_TEXT: {{ }} interpolation"]
    FitText --> Recurse["#SET_DOM(child) — recurse into grandchildren"]
  1. graph TB
  2. Node["child element"] --> PathCheck{":path attr?"}
  3. PathCheck -->|yes| SetPath["#setPath: fetch fragment, inline it, return"]
  4. PathCheck -->|no| ForCheck{":for attr?"}
  5. ForCheck -->|yes| FitFor["#FIT_FOR: expand loop, return"]
  6. ForCheck -->|no| SetIf["#setIf: :if / :else-if / :else"]
  7. SetIf --> FitModel["#FIT_MODEL: two-way form binding"]
  8. FitModel --> FitAttr["#FIT_ATTRIBUTE: :[attr] / :[css]"]
  9. FitAttr --> FitEvent["#FIT_EVENT: @[event]"]
  10. FitEvent --> FitText["#FIT_TEXT: {{ }} interpolation"]
  11. FitText --> Recurse["#SET_DOM(child) — recurse into grandchildren"]

Elements whose visibility is still pending (:else-if/:el-if/:else siblings not yet resolved by #setIf) are skipped on this pass; #setIf re-invokes #SET_DOM on the parent once it has removed the losing branches.

Directive Behavior


:path — async fragment loading


Applies only to elements carrying a :path attribute. #setPath fetches the target URL, injects the returned HTML as child nodes, and re-runs #SET_DOM on the fragment (unless the fragment contains a new PD construction, in which case it's left untouched). Script tags found in the fragment are moved to the end of document.body and executed; everything else is unwrapped in place, and the original placeholder node is removed. A fetch failure also removes the node.

:for — loop expansion


Supports three forms: item in items, (item, index) in items, and (key, value) in object. #FIT_FOR clones the template node once per array entry (or object key), binds subItem = { [val0]: item, [val1]: index } (or { [val0]: key, [val1]: value }), and renders each clone's attributes/events/text into a DocumentFragment. Nested-object items get a full recursive #SET_DOM pass; primitive items only get attribute/event/text substitution.
The fragment is then inserted with Element._child, which converts any value that is not an Element into a text node, so the loop's output in the page is the literal text [object DocumentFragment] at the original node's position:
  1. <ul id="app">
  2. <li :for="(item, index) in items">{{ index }}: {{ item }}</li>
  3. </ul>
  4. <script>
  5. "#app".RJS({ data: { items: ["dom", "template"] } });
  6. console.log("app".$.innerHTML.trim());
  7. </script>
Live preview · @pardnchiu/renderjs@2.0.3

:if / :else-if / :el-if / :else


#setIf collects the :if node and any immediately-following :else-if/:el-if/:else siblings into one group, evaluates each condition in order, and removes every node except the first one that matches (later matches in the group are removed even if their own condition is true). Supported operators: >, <, >=/>==, <=/<==, ==/===, !=/!==. ==/!= special-case the literals null, true, false, and empty (empty-string check) before falling back to string equality.
After the group is resolved, #SET_DOM keeps walking the removed nodes; reading their $i index throws a TypeError with the message "Cannot read properties of null (reading 'children')". The DOM is already in its final state when the error is thrown.
  1. <div id="app">
  2. <p :if="score >= 90">Grade: A</p>
  3. <p :else-if="score >= 60">Grade: pass</p>
  4. <p :else>Grade: fail</p>
  5. <p :if="note == empty">No note</p>
  6. <p :if="active == true">Active</p>
  7. </div>
  8. <script>
  9. "#app".RJS({
  10. data: { score: 75, note: "", active: true }
  11. });
  12. </script>
Live preview · @pardnchiu/renderjs@2.0.3

:model — two-way form binding


#FIT_MODEL inspects the bound element's type: checkbox/radio inputs listen on change and join all checked values with ,; select listens on change; plain input/textarea listen on both keyup and change. In every case the handler writes straight into the data object passed to that render pass — there is no observer or reactive re-render triggered by the write.
  1. <div id="app">
  2. <input :model="name" placeholder="Type a name">
  3. <select :model="plan">
  4. <option value="free">Free</option>
  5. <option value="pro">Pro</option>
  6. </select>
  7. <button @click="show">Show data</button>
  8. <pre id="out"></pre>
  9. </div>
  10. <script>
  11. const app = "#app".RJS({
  12. data: { name: "", plan: "free" },
  13. event: {
  14. show: function () {
  15. "out".$.textContent = JSON.stringify(app.data);
  16. }
  17. }
  18. });
  19. </script>
Live preview · @pardnchiu/renderjs@2.0.3

:[attr] / :[css] — attribute and style binding


#FIT_ATTRIBUTE collects every attribute matching /^:[\w\-]+$/ (excluding the directive names above), resolves its value through #GET_VALUE, and hands it to #SET_ATTRIBUTE. :class calls _class() (see Element Extensions); :id/:src/:alt/:href/:html map directly onto the matching DOM property; any other camel-cased key that exists on element.style is treated as a CSS property; and every binding, including the cases above, is also written as a plain HTML attribute of the same name without the colon (or that attribute is removed when the resolved value is empty).
  1. <div id="app">
  2. <a :href="link.url" :class="link.cls" :color="link.color">{{ link.text }}</a>
  3. <br>
  4. <img :src="logo" :alt="link.text" width="160">
  5. </div>
  6. <script>
  7. "#app".RJS({
  8. data: {
  9. link: { url: "https://github.com/pardnchiu/renderjs", cls: "primary", color: "steelblue", text: "RenderJS" },
  10. logo: "/assets/cover.png"
  11. }
  12. });
  13. </script>
Live preview · @pardnchiu/renderjs@2.0.3

@[event] — event binding


#FIT_EVENT matches attributes like /^@[\w]+$/, rewrites @click to onclick, and looks up the handler name in this.event. Inside a :for loop, the handler name can itself be a per-item value (resolved through the same key-path lookup used for {{ }} interpolation) rather than a fixed method name.
  1. <div id="app">
  2. <button @click="greet">Click me</button>
  3. <p id="msg"></p>
  4. </div>
  5. <script>
  6. "#app".RJS({
  7. event: {
  8. greet: function () {
  9. "msg".$.textContent = "Clicked";
  10. }
  11. }
  12. });
  13. </script>
Live preview · @pardnchiu/renderjs@2.0.3
中文