A tiny Backbone + Handlebars view framework


A tiny Backbone+ Handlebarsview framework.


bower install handlebones

For new projects give the Handlebones Generatora try. Edge production and development downloads:

Handlebones is designed to be used without RequireJS or with RequireJS without using a shim. Handlebones requires Underscore, Backbone and Handlebars plus jQuery or Zepto. The upcoming version of Backbone will remove DOM libs as a hard dependency, Handlebones was designed with this in mind.


name & HTML Attributes

  • A data-view-cidHTML attribute is always set on the view's el.
  • Adding a nameattribute to your view class will provide additional information in your stack traces when an error occurs.
  • Setting a namewill also set a data-view-nameproperty on your view's el.


A compiled template.

  template: Handlebars.compile("Hello world!")


A function that will return the context which will be available to the View's template. Defaults to function () { return this; }.

  template: Handlebars.compile("{{greeting}} world!"),
  context: function () {
    return {
      greeting: "Hello"

render([html or template])

Replaces the innerHTMLof the view's elwith output of the templatewhich will be passed the context. renderwill automatically be called by appendToif the view has not yet been rendered.

An HTML string or compiled template may be passed to renderto be used instead of the template.

The rendermethod will trigger a renderevent.

appendTo(element or function)

Appends the view to the passed elementwhich must already be appended to the document. renderwill be called if it hasn't yet be called, and a readyevent will be triggered.


By default appendTowill use appendChildas the DOM insertion operation, alternatively a function can be specified to run whatever insertion operation you wish. Before the function executes renderwill be called if needed and readywill be triggered after the function executes.


An event that is fired when a view is attached to the documentwith appendTo.

view.on("ready", function () {

The readyevent will fire on any childrenthat are already part of the view and any new childrenthat are added after the readyevent has fired.


Calls removeChildon all children, and also triggers a removeevent in addition to the existing Backbone listenTocleanup behavior. Once removed a view should no longer be used.

The removeevent should be your main hook to do any garbage collection behaviors. Note that while removeChildis called on all children, removeis notcalled on children.

  intiailize: function () {
    this.child = this.addChild(new AnotherView());
    this.listenTo(this, "remove", function () {


Adds the passed view to the childrenobject and sets the parentof the passed view to the caller. In order to embed a child with the viewhelper, addChildmust be used.


Removes the passed view from the childrenobject and sets the passed view's parentattribute to null. removeChildis automatically called on all childrenwhen removeis called. Note that removeis notcalled automatically on children.


An object containing all views added with addChildindexed by each views' cid.


A reference to the parent view if any. Set when addChildis called.


A view which will embed a single child view, which can be changed with setView. As new views are set, old views are removed. Useful in conjunction with a Backbone.Router.

  routes: {
    "": "index",
    "about": "about"
  initialize: function () {
    this.layoutView = new Handlebones.LayoutView();
  index: function () {
    this.layoutView.setView(new IndexView());
  about: function () {
    this.layoutView.setView(new AboutView());

setView(view [,callback])

Set the current view. removewill be called on the view that was previously set.

To perform asyncronous operations (such as an animation) an optional callback option may be specified which will receive the new view, the old view, a function which will perform the append operation and a function which will perform the remove operation.

view.setView(newView, function (newView, oldView, append, remove) {
  $(oldView.el).fadeOut(function () {


Gets the currently displayed view.


Requires a modeloption to be passed into the constructor. It calls render on itself every time the model's changeevent is fired. It also sets a contextmethod that will return this.model.attributes.


Requires a collectionoption be passed into the constructor. Creates a specified modelViewfor each modelin the collection. Will re-render the entire collection on collection resetor sortand add or remove modelViews on collection addor removeevents.

The templateproperty of a CollectionViewwill not be used to render the collection.

  tagName: "ul",
  modelView: Handlebones.ModelView.extend({
    tagName: "li",
    template: Handlebones.compile("item content")
  emptyView: Handlebones.View.extend({
    tagName: "li",
    template: Handlebones.compile("empty content")


The view class to use when creating new views for each model in the collection. Defaults to Handlebones.ModelView.


The view class to use when creating a view to show when the collection is empty. Defaults to false.


The classNameto add or remove from the view's eldepending on wether or not the collection is empty. Defaults to empty

appendModel(model [,index])

Renders a modelViewfor a given model and appends it to the view. This method is used by renderin a loop.

Accepts an optional numeric indexargument to tell the view where to place the generated modelView. The passed model is not required to be part of the view's collection.

An appendModelevent will be fired for each rendered view. The event handler will receive the passed modeland associated modelView.


Removes a modelViewassociated with a given model. Triggers a removeModelevent which will receive the passed modeland associated modelView


An optional function that can be specified which will hide or show modelViews based on the specified criteria.

  itemFilter: function (model) {
    return model.get("someKey") === "someValue";

On collection reset, add, removeor a model changethe modelFilterwill be automatically re-applied.


When the modelFilteritself changes (for instance the search criteria for an auto-complete UI) call this method to force the view to re-filter it's collection.


{{view child}}

Embed one view inside of another. You must add the view to be embedded with the addChildmethod.

  initialize: function () {
    this.child = this.addChild(new OtherView());
  template: Handlebars.compile("{{view child}}")


tag(attributes, content, context)

Generate arbitrary HTML. tagor tagNamemay be specified to define what type of tag will be generated. classor classNamemay be passed to specify the HTML class. All other attributes will be passed through unmodified. If a contextargument is passed Handlebars tokens inside of attributes will be evaluated with the given context.

  tag: "a",
  href: "articles/{{id}}"
}, "link text", {
  id: "42"


Obtains a reference to the nearest viewfrom a given element. Especially useful inside of a CollectionView

  tagName: "ul",
  events: {
    "click li": function (event) {
      var modelView = $(event.target).view();
      var model = modelView.model;
  modelView: Handlebones.ModelView.extend({
    tagName: "li",
    template: Handlebars.compile("...")

Catalog of Built in Events

  • render (View)
  • ready (View)
  • remove (View)
  • appendModel (CollectionView)
  • removeModel (CollectionView)


npm install -g mocha-phantomjs phantomjs

To run tests in browser:

gulp connect
open http://localhost:8080/jquery.html









扫码加入 JavaScript 社区