view.json

Runtime

The runtime consists of:

  • View prototypes
  • App scope
    • DOM manipulation shim functions
    • Event registration function
    • Binding resolution function

The generated markup

I think the easiest way to understand view.json is to just look at the base template for a view. Here is what a single view looks like:

function %name%() {
  var b = this.bound = [];
  this.children = %child_block%;
  this.listeners = %listener_block%;
  this.dom = %dom_event_block%;
}

%name%.prototype = new View();

%name%.prototype.render = function() {
  var b = this.bound;
  for(var i = 0; i < %bound_count%; i++) {
    b.push(id());
  }

  return %embed%;
};

module.exports = %name%;

Basically, given the right JSON, we generate a view object with the right metadata, and a custom render() function that contains the HTML for the view, and references to any child views.

For example, this view.json:

{ name: "ItemView", content: 'Foo' }

Describes:

<div>Foo</div>

Views extend the View object, which has the following functions:

  • render(): renders the view and all of it's child views HTML as a string.
  • appendTo(el): renders the view and it's child views, attaches the HTML to the DOM, registers DOM event handlers and registers event listeners, and finally updates the HTML with any bound values. More on all that next.

Common keys:

  • name: sets the classname of the view
  • tag: sets the tag of the view
  • attr: sets an attribute value
  • id: sets the id of a named view

Writing view functions

view.json does not reinvent the object model. It uses native prototypes.

To write view functions, you add them to the prototype:

TodoListItem.prototype.toggle = function() {
  this.model.set('done', !this.model.get('done'));
};

And refer to them via the view variable:

{
  name: "TodoListItem",
  on: { click: "view.toggle();" }
}

Traversing the view hierarchy

The views store references to their own children. If you do something like this:

window.App = new Views.TodoApp();
window.App.appendTo('body');

then you can inspect the full view hierarchy by looking at window.App and its children (under the children property of the view instance).