Writing a helper that produces bound results?

2019-01-18 04:04发布

I have a date/time formatting helper but what it produces does not update when the underlying property changes. This is not a surprise, but does anyone know how to produce bindings in helpers?

I invoke the helper like this...

{{timestamp created_at}}

...and here is the helper itself:

Handlebars.registerHelper('timestamp', function(context, options) {
  var formatter        = options.hash['format'] ? options.hash['format'] : 'hh:mm a MM-DD-YYYY';
  var original_date    = Ember.getPath(this, context); // same as this.get(context) ?
  var parsed_date      = moment(original_date);
  var formatted_date   = parsed_date.format(formatter);

  return new Handlebars.SafeString("<time datetime=" + original_date +">" + formatted_date + "</time>");
}); 

3条回答
Anthone
2楼-- · 2019-01-18 04:41

It is now possible to create bound Handlebars helpers using a public Ember API.

Handlebars.registerBoundHelper('timestamp', function(date, options) {
  var formatter        = options.hash['format'] ? options.hash['format'] : 'hh:mm a MM-DD-YYYY';
  var parsed_date      = moment(date);
  var formatted_date   = parsed_date.format(formatter);

  return new Handlebars.SafeString("<time datetime=" + date +">" + formatted_date + "</time>");
});

The parameter passed to the helper will have already been resolved, and the helper will be called again whenever the path changes.

查看更多
Lonely孤独者°
3楼-- · 2019-01-18 04:54

Not sure if this applies to this particular question, but I also created helpers in views and wanted the values to update when data in the Ember.js view changed. The way I solved this problem was to write an observer on the values I wanted changed and used jQuery to update the specific value.

For example (in Coffeescript):

...

attrObserver: Ember.observer(() ->
  $("#attrId").text(this.get("attr"))

...
查看更多
Explosion°爆炸
4楼-- · 2019-01-18 04:56

It is unfortunately more complex than I'd like to create a custom helper with bound content. Here's an example that Peter Wagenet wrote: https://gist.github.com/1563710

I'll be lobbying for this to become easier.

查看更多
登录 后发表回答