handlebones

A tiny Backbone + Handlebars view framework

Handlebones

A tiny Backbone+ Handlebarsview framework.

Usage

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.

Handlebones.View

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.

template

A compiled template.

Handlebones.View.extend({
  template: Handlebars.compile("Hello world!")
});

context()

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

Handlebones.View.extend({
  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.

view.appendTo(document.body);

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.

ready

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

view.on("ready", function () {
  view.$("input").focus();
});
view.appendTo(document.body);

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

remove()

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.

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

addChild(view)

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.

removeChild(view)

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.

children

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

parent

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

LayoutView

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.

Backbone.Router.extend({
  routes: {
    "": "index",
    "about": "about"
  }
  initialize: function () {
    this.layoutView = new Handlebones.LayoutView();
    this.layoutView.appendTo(document.body);
  },
  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 () {
    remove();
    append();
    $(newView.el).fadeIn();
  });
});

getView

Gets the currently displayed view.

Handlebones.ModelView

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.

Handlebones.CollectionView

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.

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

modelView

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

emptyView

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

emptyClassName

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.

removeModel(model)

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

modelFilter

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

Handlebones.CollectionView.extend({
  itemFilter: function (model) {
    return model.get("someKey") === "someValue";
  }
});

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

updateModelFilter()

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.

Helpers

{{view child}}

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

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

Util

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.

Handlebones.Util.tag({
  tag: "a",
  href: "articles/{{id}}"
}, "link text", {
  id: "42"
});

$.view(event.target)

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

Handlebones.CollectionView.extend({
  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)

Testing

npm install -g mocha-phantomjs phantomjs
gulp

To run tests in browser:

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

HomePage

http://handlebonesjs.org

Repository

https://github.com/FormidableLabs/handlebones.git


上一篇:hans
下一篇:handlebars-precompiler

相关推荐

暂无相关文章

官方社区

扫码加入 JavaScript 社区