2

I'm trying to use Handlebars helper, but the helper view does not get updated.

The view,

<script type="text/x-handlebars">
  {{#view App.NumberView}}
    <button {{action changeNumber}}>Change number</button><br>
    {{formatNumber view.number}} <br>
    {{view.number}}
  {{/view}}
</script>​

The code,

App = Ember.Application.create({});

App.NumberView = Ember.View.extend({
  number: 5,
  changeNumber: function(e) {
    this.set('number', this.get('number') + 1);
  }    
});

Em.Handlebars.registerHelper('formatNumber', function(timePath, options) {
  var number = Em.Handlebars.getPath(this, timePath, options);
  return new Handlebars.SafeString("Formated number: " + number);
});

​ The live example in jsfiddle http://jsfiddle.net/LP7Hz/1/

So what's wrong ?

4

2 回答 2

3

因为 Ember 中的 Handlebars 助手不是绑定助手。所以你可以实例化一个辅助视图来做到这一点,就像这个小提琴:

http://jsfiddle.net/secretlm/qfNJw/2/

HTML:

<script type="text/x-handlebars">
    {{#view App.NumberView}}
        <button {{action changeNumber}}>Change number</button><br>
        {{formatNumber view.number}} <br>
        {{view.number}}
    {{/view}}
</script>​

Javascript:

App = Ember.Application.create({});

App.NumberView = Ember.View.extend({
    number: 5,
    changeNumber: function(e) {
        this.set('number', this.get('number') + 1);
    }    
});


App.registerViewHelper = function(name, view) {
  Ember.Handlebars.registerHelper(name, function(property, options) {
    options.hash.contentBinding = property;
    return Ember.Handlebars.helpers.view.call(this, view, options);
  });
};


inlineFormatter = function(fn) {
  return Ember.View.extend({
    tagName: 'span',

    template: Ember.Handlebars.compile('{{view.formattedContent}}'),

    formattedContent: (function() {
      if (this.get('content') != null) {
        return fn(this.get('content'));
      }
    }).property('content')
  });
};


App.registerViewHelper('formatNumber', inlineFormatter(function(content) {

    return new Handlebars.SafeString("Formated number: " + content);
}));

这个链接很有用:http : //techblog.fundinggates.com/blog/2012/08/ember-handlebars-helpers-bound-and-unbound/ 来自@Jo Liss ​</p>

于 2012-09-26T14:40:26.260 回答
1

You're looking for a bound helper, which doesn't exist just yet. There is a Pull Request and associated discussion.

于 2012-09-26T12:21:20.803 回答