Handlebars helpers in Ember.js

I've been trying to get a seemingly simple Handlebars helper in place so that I can mark an element as active in an {{each}} block if it's ID matches that of the selected one.

Here's one attempt using some helper I found online.

Handlebars.registerHelper('ifequal', function (val1, val2, fn, elseFn) {
    console.log(val1);
  console.log(val2);
  if (val1 === val2) {
    return fn();
  } else if (elseFn) {
    return elseFn();
  }
});

A friend of mine also has a fiddle for a more 'Handlebars-way' attempt.

So before everyone tells me to wrap my element in a view and use didInsertElement or something, let me ask my actual question: Are handlebars helpers in ember broken in this instance? My helper is expecting a value and it's getting a string. Is that expected behaviour?


Looks like this is normal behaviour,

You can try something like:

var getPath = Ember.Handlebars.getPath;
Handlebars.registerHelper('ifequal', function (val1, val2, options) {
  var context = (options.fn.contexts && options.fn.contexts[0]) || this;
  var val1 = getPath(context, val1, options.fn);
  var val2 = getPath(context, val2, options.fn);
  console.log(val1);
  console.log(val2);
  if (val1 === val2) {
    return options.fn(this);
  } else{
    return options.inverse(this);
  }
});

Fiddle: http://jsfiddle.net/73wtf/28/

Ref1: https://github.com/emberjs/ember.js/blob/master/packages/ember-handlebars/lib/helpers/debug.js Ref2: http://handlebarsjs.com/block_helpers.html


In registerHelper , it's passing the binding string instead of the actual value to your function. So you can use getPath to get the actual value. Anyway, I'd agree this behavior seems 'unnatural'. I guess the reason to use binding string is to make the auto-updating work.

链接地址: http://www.djcxy.com/p/61584.html

上一篇: 在Ember手柄中使用嵌套的每个块时的上下文绑定

下一篇: Ember.js中的把手助手