The JavaScript blog.


libraries node modules components react-native react

React Component Playground, React Native Fish

Posted on .

React Component Playground

I have a backlog of React submissions, so I thought I'd work through them rather than spacing them out over a few weeks. First, React Component Playground (GitHub: FormidableLabs/component-playground, License: MIT, npm: component-playground) by Ken Wheeler is a React component that allows you to edit a React component with a live preview. You can try it out on the project's homepage -- see the button example near the top.

Normally with React/Angular/etc. you're constantly waiting for the build/refresh cycle, but with this project you can experiment a little bit to get results more quickly. As the example suggests, this is useful when working with React styles.

The same author also wrote nuka-carousel (GitHub: kenwheeler/nuka-carousel, License: MIT, npm: nuka-carousel), which is a React carousel component.

React Native Fish

Fish example

If you're looking for a fun React Native project, then check out Ivan Starkov's react-native-fish (GitHub: istarkov/react-native-fish). It's a graphical experiment that generates a trial of objects that looks like a fish. It's pure JavaScript and doesn't use any images.

It's interesting to see how React Native can be used to draw abstract things that aren't NSWhateverViews. I noticed that it uses arrays from the gl-matrix module, and immutable.


libraries components react

React Roundup: rc-calendar, D3 React Reusable Charts, tcomb-form

Posted on .


rc-calendar (GitHub: react-component/calendar, License: MIT) by yiminghe is a port of kissyteam/date-picker that allows you to render calendars with React.render(<Calendar />, container). It has props for locale, showing today, and the select/blur events, and it includes some examples and tests.

The supported locales are en-us and zh-cn, so you can actually display a Chinese calendar UI. It also supports aria and keyboard accessibility.

D3 React Reusable Charts


D3 React Reusable Charts (GitHub: jdarling/d3rrc, License: MIT, npm: d3rrc) by Jeremy Darling is a graph library that supports bar charts, pie charts, scatter charts, and time series. It allows you to use a LineChart element. This code is taken from the multi-line chart example:


React makes graphs quite clean by allowing you to mix the markup and JavaScript data. For more examples, take a look at the full d3rrc example list.


tcomb-form (GitHub: gcanti/tcomb-form, License: MIT) by Giulio Canti is a UI library for making forms. As we all know, making forms is web development drudgery, so anything to take the pain away is welcome. Giulio's library is "domain driven", which means it's able to generate a form based on the domain model.

There's a personal form example that shows the kind of form I've spent all too much time creating in the past. The source uses a kind of strongly typed model definition approach:

var t = require('tcomb-form');

var Gender = t.enums({  
  M: 'Male',
  F: 'Female'

var Country = t.enums({  
  US: 'United States',
  IT: 'Italy'

var Person = t.struct({  
  fullName: t.Str,
  nickname: t.maybe(t.Str),
  gender: Gender,
  country: Country,
  tags: t.list(t.Str)

var Form = t.form.create(Person, {  
  auto: 'labels',
  fields: {
    gender: {
      factory: t.form.radio

You don't have to use this to define the actual models in your application. With this library, it might be better to use a lightweight model/view model approach, so you'd treat the tcomb models as view models that define the behaviour specific to forms.


libraries ui angularjs components

Backbone setMatch, Smalleditor

Posted on .

Backbone setMatch

Backbone setMatch (GitHub: joshbambrick / setMatch, License: MIT) by Joshua Bambrick allows you to match models in a collection based on attributes other than the id. This is applied whenever set is called on a collection, both explicitly and internally by Backbone.

The setMatch property can be used with arrays, so you can pass a set of names to match. If you pass it an object you can set options, including the id option which controls what happens when set is called. When it's set to inherit and incoming models have an id, then match models in the collection will inherit that id, but using retain will keep the original value instead.


Smalleditor (GitHub: jdkanani / smalleditor, License: MIT, Bower: smalleditor) by Jaynti Kanani is a WYSIWYG editor inspired by Medium. It requires AngularJS, and features revision tracking.

Deltas can be applied to revisions to get the next revision:

angular.module('smalleditorDemo', ['ngRoute', 'smalleditor'])  
.controller('EditorController', ['$scope', function($scope) {
  $scope.$watch('editorApi', function(editor) {
    // Get current data model
    var baseDataModel = editor.dataModel();

    // After editing for a while get new data model
    var currentDataModel = editor.dataModel();

    // Compute delta between baseDataModel and currentDataModel
    var delta = editor.computeDelta(baseDataModel, currentDataModel);

    // Apply that delta to any revision to get next revision
    editor.applyDelta(nRevision, nDelta);

The author cites MediumEditor, which is a similar project that is more focused on the UI and less on the revision tracking aspect.

Yet another alternative is the Pen Editor -- the nice thing about Pen is it supports Markdown.


tutorials components

Introducing Web Components to Control Authors

Posted on .

This is a guest post by Matthew Phillips, from Bitovi. You can find him on Twitter: @matthewcp and GitHub: matthewp.

At this point unless you've been living under a rock you've likely heard at least a little about web components, a collection of emerging standards created with the intent of making web development more declarative. Among other things, web components allow for custom elements, an easier way to encapsulate your widgets. If you've been developing with MVC frameworks there is a learning curve to using components, but once things start to click you'll want to use them everywhere in your application. Who hasn't wanted an easy way to insert a random cat picture?

<randomcat width="200" height="300"></randomcat>  

Creating widgets that are well encapsulated is something we do on a daily basis on as JavaScript engineers. In this article I'll explain where traditional control-based MVC has fallen short of that goal and how web components can resurrect the ease of development from the web's early roots.

MVC's Brick Wall

Traditional MVC frameworks encourage you to organize your view code by creating constructor functions called Controls or Views. If you've developed in this way you probably recognize some of the problems you encounter with this approach.

Tracking Down Instantiation

Since Controls are implemented as constructor functions that operate on a template, any sub view must be manually instantiated within one of the control's lifecycle methods, usually either init or render. Consider the following in Backbone:

var Widget = Backbone.View.extend({  
  initialize: function() {
    this.subView = new InnerWidget({ el: $('#inner') });

  render: function() {

That's a lot of code that will become more complex as you add additional subviews or conditions for rendering.

(Lack Of) External API

While creating a widget, its common to create an external API to interact with. With traditional MVC controls, there is no standard way to do this, so it ends up being ad-hoc at the whim of the author. For example, here's an accordion containing Panel subviews:

var PanelView = Backbone.View.extend({  
  template: _.template($('#panel-tmpl').html()),

  render: function() {
    return this.$el;

var AccordionView = Backbone.View.extend({  
  template: _.template($('#acc-tmpl').html()),

  addPanel: function() {
    if (panel instanceof PanelView) {

And then to use this:

var panel = new PanelView({ model: data });  

You'll want to abstract some of these pain points to create your own "standard API" for controls. You'll probably create some base classes with stub functions for common tasks. Pretty soon you've created your own mini-framework. We're learned to put up with these little things and they don't bother us day-to-day, but when you discover a better way it will change the way you architect your application.

Hidden Model

Similarly, widgets commonly need to interact with external model data. Most MVC frameworks provide some way to pass data into the control so a lot of people have established a pattern of passing in a "model" property to fill this hole. Having a clearer way of setting the model for a control opens a lot of doors in terms of composability. With the traditional control pattern you usually wind up using an adhoc ViewModel created with some properties passed in to the constructor and some created as part of the control's own logic.

Enter Web Components

Web Components are a W3C spec for an HTML and JavaScript construct that, at its heart, is a way to define custom HTML elements. The spec includes:

  • Native templates (spec)
  • A way to load them (spec)
  • A method to define custom elements and extend existing ones (spec)
  • Hooks to run functions when an element is inserted in the page.

A custom element can be as complex as the main router for single page application, a simple widget to display markdown inline:

<x-markdown table-of-contents-depth="2">  
# Heading

## Sub-heading

* List item
   - Sub list item

or as simple as a way to embed a YouTube video.


Web Components provide an alternate way to define traditional MVC based controls, with several key advantages.

Maximal Encapsulation

The power of web components is their ability to easily encapsulate the details of a widget while still maintaining the ability to compose them together, thanks to the legacy of HTML's document-oriented roots. Because it is layout-based, web components can be neatly organized in templates, solving the instantiation problem that a control-based workflow suffers from. Applications can become more template driven rather than instantiating controls with complex event handler logic. Let's say you were A/B testing a feature, you could have your template (in Mustache) look something like this:

{% raw %}
{{if randomlyPicked}}
{% endraw %}

Obvious API layer

The API layer for web components is easy to understand. Data is passed to components through HTML attributes.

<x-injector href="/some-page.html" />  

Layout is passed through the element's inner content, as shown in the markdown example above.

Models and Templates

The web components spec includes templates for the first time in the web's history. This means no more script tag or hidden div hacks to include templates on a page. Templates allow you to create fragments of markup to be used by your components later. They are parsed, but not rendered until inserted into the page.

Models can be bound to the templates, and, through the power of Object.observe changes in the model, would result in relevant parts of the template being automatically rendered. If you've used an MVC framework with template binding and observable models you're probably already familiar with this.

Models are passed into components the same way as all types of data, through attributes.

With CanJS' can.Component you can pass the name of your model through the attributes and get the live-binding today, without waiting for standardization to flesh out that part of the spec. This brings me to my last point…

Using Web Components today

Despite this being early days for Web Components, there are already a few options if you are interested in getting started. Polymer and X-Tags are two projects started by Google and Mozilla engineers working on the Web Components spec. These projects are bleeding-edge and break compatibility often. Additionally they don't attempt to extend the spec with functionality that won't eventually end up in it. What they do offer you is the ability to start using components the way they will be used when browsers have fully implemented the specifications. can.Component, on the other hand, is an early implementation of Web Components that provides additional functionality that is beyond the scope of custom elements.

can.Component adds two-way binding between a component's model (which is not yet part of the web component spec) and its form elements. Additionally it adds declarative binding to a component's templates through it's scope object. Scope is an object that is used to render the template, but with the addition of declarative binding it does much more than that. The scope can be used to update the state of a component and respond to events. Here's a typical example of can.Component that shows off all of these features:




{% raw %}
<script id="color-section-template" type="text/mustache">  
    <span class="validations">{{validationMessage}}</span>
    <input name="name" type="text" can-value="color" can-change="validate">
{% endraw %}

This is the component's JavaScript:

  tag: "color-selection",
  template: can.view("#color-selection-template"),
  scope: {
    color: "blue",
    validate: function() {
      if (!isAColor(this.attr("color"))) {
        this.attr("validationMessage", "Not a valid color");
      } else {

We Still Need Libraries

I hope I've demonstrated the way in which web components breaks some of the boundaries we've hit with traditional control-based MVC. At the same time the specification is intentionally low level and leaves room for libraries to improve upon the experience, as can.Component is doing today.

As a consequence of Web Component's inherent declarative nature your code will become more condensed, with far less boilerplate. We're truly approaching a paradigm where separation of concerns is being achieved. But you can't appreciate the way web components changes the way you write applications until you try it yourself. So I encourage you to choose a library and start on your first widget today.

Further (required) Reading


libraries jquery ES6 components

Chained, Door

Posted on .


Chained (GitHub: vzaccaria / chained, License: MIT) is another ES6 experiment. It allows APIs that return promises to be mixed with functions that take parameters and return mutated objects. In Vittorio's example he mixes jQuery's network methods with Underscore.js to download JSON and then filter it:

getUser = (user) ->  
    .filter(-> /package/.test(arguments[0]))
    .map(-> "https://npmjs.org#{arguments[0]}")


In this CoffeeScript example, methods that use promises (get) are mixed with functions that take objects as the first argument (filter, map), using a consistent chainable API. To make this work, Vittorio has used ES6's introspection features.

The project has detailed notes in the readme about how this works. He mentions that the library came about after trying to create DSLs with JavaScript.


Olivier Wietrich sent in Doors (GitHub: bredele / doors, License: MIT, component: bredele/doors), a module for conditionally restricting access to open events that are triggered when all locks are unlocked.

[State machines and promises] both have something missing. A transition occurs when one condition is triggered. Things are not so simple in real life. You will probably have more than one condition to do something, but one condition is sufficient to not do it. Think about a door with multiple locks: you can't open the door until all locks are unlocked.

Looking at the documentation, it seems like the author wants to use it to restrict access to an API until certain authentication preconditions are met. There's a simple HTML example that uses a graphical door, and two locks. You can toggle locks and add more.