简体   繁体   中英

Ember.js Handlebars block helper

Apparently this does not work: http://jsbin.com/efapob/3/edit

Ember.Handlebars.registerHelper('foo', function(options) {
  var result = 'BEFORE '
           + options.fn(this)
           + ' AFTER';
  return new Handlebars.SafeString(result);
});

And I assume it's because the fn() writes directly to the output buffer.

However, I need a way to directly work with the output of the block's content.

I tried overwriting a view's render function, but that also didn't lead me anywhere.

(Background: I'm trying to write an {{#ifchanged}} helper block that only renders if the contents have changed in comparison to the last call. The use case is a loop that should display something every time one property of the model is different to the last one. If you have other ideas how to achieve this, comments very appreciated!)

If anyone is interested, in this specific use-case I worked around the issue of not being able to use the return of fn() like so:

var ifchanged_last;
Ember.Handlebars.registerHelper('ifchanged', function(property, options) {
  var value = Ember.Handlebars.get(this, property);
  if (value !== ifchanged_last) {
    options.fn(this, options);
  }
  ifchanged_last = value;
  return;
});

Template:

{{#each content}}
  {{#ifchanged some_key}}
    The value changed
  {{/ifchanged}}
{{/each}}

Large room for improvement, but a usable starting point.

You can use isDirty property from DS.Model to know when the data changes.

In some template:

{{#if isDirty}}
    You changed the model<br/>
{{/if}}

And a jsfiddle with the demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM