Skip to content

Instantly share code, notes, and snippets.

@juliocesar
Created December 12, 2012 00:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juliocesar/4263855 to your computer and use it in GitHub Desktop.
Save juliocesar/4263855 to your computer and use it in GitHub Desktop.
Using Backbone.View with regular (read: not all rendered in JS) HTML pages.

The idea is you can still use Backbone.View to structure components in the screen. Run the code below with each page render.

In CoffeeScript:

$ ->
  for el in $('[data-view]')
    $el = $ el
    viewName = $el.data 'view'
    view = window[viewName]
    new view(el: el) if view?

In JavaScript:

$(function() {
  $('[data-view]').each(function(el) {
    var $el = $(el),
        viewName = $el.data('view'),
        view = window[viewName];
    if (view) new view({el: el});
  });
});

The assumption above is every view class is accessible from the window namespace, and this goes against the visibility principles of AMD. I say: get over it.

Now in your markup, declare which view controls a certain piece of markup by doing:

<section class="new-post" data-view="NewPostView">
  ...
</section>

Voila. Backbone views working with regular page renders.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment