Paul Cowan

Nomadic cattle rustler and inventor of the electric lasso

Ember.js - Programmatically Bind From a Handlebars Helper

Warning: The examples use Ember 1.7.1

This is a quick update to my last post where I created a helper that bound data from an external json hash.

One problem I ran into was that if I was not creating links via the link-to helper then the properties were not bound. In line 11 of the gist below, I am returning a simple string that will render the unbound property wrapped in a span tag.

bad.js
1
2
3
4
5
6
7
8
9
10
11
12
Ember.Handlebars.registerBoundHelper('getProperty', function(context, property, options) {
  var defaults, prop;
  defaults = {
    className: "",
    context: "this",
    avatar: false
  };
  property = Ember.merge(defaults, property);
  prop = context.get(property.binding);
  if (!property.hasOwnProperty("route")) {
    return new Handlebars.SafeString("<span>" + prop + "</span>");
  }

The solution was to call out to the handlebars bind helper after updating the options hash on lines 2-5 below:

good.js
1
2
3
4
5
  if (!property.hasOwnProperty("route")) {
    options.contexts = [context];
    options.types = ["ID"];
    return Ember.Handlebars.helpers.bind.call(context, property.binding, options);
  }

Here is an updated jsbin with a full working example.

I am not sure if this is relevant for life after ember 1.7.1 but these techniques have worked well for me thus far.

Comments