Ractive.js – by example



Ractive.js – by example

1 2


ractive-js-example-presentation

A simple presentation showing an example use of Ractive.js

On Github zzolo / ractive-js-example-presentation

Ractive.js

by example

Created by Alan Palazzolo

ractivejs.org

zzolo.org/ractive-js-example-presentation

What is Ractive.js?

Data binding,

DOM updates,

Event handling

Model-View-Controller

AngularJS

Ember

Backbone(.stickit)

Bus Stop

Data

http://svc.metrotransit.org/NexTrip/43275?format=json
[
  {
  "Actual": true,
  "BlockNumber": 1122,
  "DepartureText": "3 Min",
  "DepartureTime": "/Date(1377800220000-0500)/",
  "Description": "Emerson/26Av-Broadway",
  "Gate": "",
  "Route": "5",
  "RouteDirection": "NORTHBOUND",
  "Terminal": "F",
  "VehicleHeading": 0,
  "VehicleLatitude": 44.9888311,
  "VehicleLongitude": -93.2898608
  },
  ...
]

Basic Template and Render

<h2>Bus Stop: {{stop}}</h2>
<ul>
  {{# buses:i}}
    <li>{{Route}}{{Terminal}} in {{DepartureText}}.</li>
  {{/ buses}}
</ul>
var $el = $('.container-output');
var template = $('#template-id');
var ractiveView = new Ractive({
  el: $el,
  template: template,
  data: {
    stop: busStop,
    buses: [ .. ]
  }
});

Styles, Mustache, and Polling

Mustache

<h2>Bus Stop: {{stop}}</h2>
<ul>
  {{# buses:i}}
    <li>{{Route}}{{Terminal}}
      {{# Actual}}
        {{ DepartureText.toLowerCase() === 'due' ? 'is Due' : 'arrives in ' + DepartureText }}
      {{/ Actual}}
      {{^ Actual}} arrives at {{DepartureText}}{{/ Actual}}.
    </li>
  {{/ buses}}
</ul>

Poll data

var ractiveView = new Ractive({
  el: $el,
  template: template,
  data: {
    stop: busStop,
    buses: []
  }
});

onBusUpdate(function(data) {
  ractiveView.set('buses', data);
});

Data Updates

var buses = { a: 1, b: 2 };
var ractiveView = new Ractive({
  el: $el,
  template: template,
  data: {
    stop: busStop,
    buses: buses
  }
});
buses.c = 4;
ractiveView.update('buses');

Array modifications

var buses = [];
var count = 0;
var ractiveView = new Ractive({
  el: $el,
  template: template,
  data: {
    stop: busStop,
    buses: buses
  }
});

onBusUpdate(function(data) {
  buses.push(data[count++]);
});