如何创建 ember 车把助手?

How to create ember handlebar helper?

大家好

我尝试创建助手

Handlebars.registerHelper('testCan', function(permissionName, options){
  var permission = Ember.Object.extend({
    testCan: function(){
      debugger;
      return true;
    }.property()
  }).create();

  // wipe out contexts so boundIf uses `this` (the permission) as the context
  options.contexts = null;

  Ember.Handlebars.helpers.boundIf.call(permission, "testCan", options)
});

并将其用作

{{#testCan read controller=controller}}
    <h1>It's works</h1>
{{/testCan}}

我这样做是为了从这里测试模式 http://livsey.org/blog/2012/10/16/writing-a-helper-to-check-permissions-in-ember-dot-js/

但是不行((

怎么了? Ember 版本 - 1.9.1

P.P.S 最初我使用现有代码(请参阅此处 )但是这个示例我已经开始尝试重现/解决该问题

如果您要检查 permissions/authorization,使用现有的插件可能是最简单的方法。我建议 ember-can or ember-sanctify(我相信 sanctify 只支持 1.10 及更高版本)。

尽管在组件内部进行推理可能更容易理解您尝试执行的操作。在实践中,我建议创建助手的唯一原因是要么进行简单的转换,要么能够传递任意数量的参数。 Ember 可以改进的其中一件事是帮助用户了解如何在助手内部做更复杂的事情。

示例组件:

app/templates/components/test-can.hbs:

{{#boundIf hasPermission}}
  {{yield}}
{{/boundIf

app/components/test-can.js:

import Ember from 'ember';

export default Ember.Component.extend({
  permission: null,
  controller: null,

  hasPermission: function() {
    //implement logic here
  }.property('permission', 'controller')
});

使用示例:

{{#test-can permission=read controller=controller}}
  Your Content Here
{{/test-can}}

不确定您的示例中的 readcontroller 是什么,因此如果这些变量没有指向任何内容,那么这不会有太大作用。希望这有帮助。

更新:

因此在 app/helpers/test-can.js 创建一个如下所示的文件

export default function(permissionName, options){
  var permission = Ember.Object.extend({
    testCan: function(){
      return true;
    }.property()
  }).create();

  // wipe out contexts so boundIf uses `this` (the permission) as the context
  options.contexts = null;

  return Ember.Handlebars.helpers.boundIf.call(permission, "testCan", options);
}

测试时不起作用?上面的例子当然总是 return true 因此总是产生块。 1.9.1 still basically uses the same code for the if helper.

相关问题https://github.com/emberjs/ember.js/issues/10692

The this context inside of helpers has changed in various versions:

this was the controller in 1.0.0 through 1.8.0 this was the view in 1.9.0 and 1.10.0 this is undefined in 1.11+ My guess is that the context change in 1.9 is causing this error, updating your helper to add the unknownProperty to the controller will fix the issue.