Declarative JS components with viewloader.js

Here’s a pattern I’ve been using lately to attach JS behaviour to a chunk of HTML.

Specify the JS component’s name in a data-view attribute:

<div data-view="dropdown">...</div>

Then upon page load (or any other event) call `viewloader.execute with an object containing one-liner setup functions for every component in the app:

viewloader.execute({
  audioPlayer: function( $el, el ) { setupAudioPlayer( el ); },
  commentBox: function( $el ) { new CommentBoxView( $el ); },
  // ...
  dropdown: function( $el ) { $el.fancyDropdown(); }  
});

Viewloader searches the DOM for every element with a data-view attribute and calls its setup function.

It’s not tied to any particular framework, so you can use it in your app to instantiate any type of component: plain old JS widgets, jQuery plugins, Backbone views. If you really wanted to, you could use it to manually bootstrap an Angular app.

I’m a big fan of writing small, isolated components; lots of little mini-apps that make up the app as a whole. Sometimes you only need a couple of lines of jQuery, sometimes you need a framework to bring a bit more structure. I like being able to mix & match the JS I write within an app while having a consistent method of bootstrapping each new component.

Viewloader itself is a whole 13 lines of code (though it relies on jQuery or Zepto… if you’re not using either of those you should be able to tweak it to suit your needs).

viewloader on GitHub

PS: Mad props to Toby for introducing me to this idea.

Comments