从另一个助手调用助手

时间:2016-05-07 01:04:28

标签: ember.js

我有一个模板,其中包含项目的背景图片:

{{#each model as |item|}}
   <div style="background-image: url('img/backgrounds/{{item.imageBackground}}');">
   {{image.title}}
   </div>
{{/each}}

这当然不好,因为不推荐使用对style-attribute的绑定 所以我在我的控制器上创建了一个计算属性,用于绑定htmlSafe字符串,该字符串按预期工作。

因为我需要这个 - 以及绑定到特殊链接的图像 - 在几个模板中我制作了2个我想要/试图组合的帮助者:

第一个帮助器在其他几个模板中完美运行(生成一个params-string /指向提供所需图像的php文件的链接)

 // helpers/imagelink.js
 export default Ember.Helper.extend({
    empty: "img/dummies/blank.png",
    compute(params, hash) {
        if(params[0]) {
           let paramString = 'file='+params[0]+'&itemType='+hash.item+'&type='+hash.type;
           return ENV.ajaxPrefix + ENV.apiNamespace + '/getimage?'+paramString;
        } else {
            // display dummy
            return this.get('empty');
        }
    }

});

现在我想制作第二个帮助器,以某种方式封装第一个帮助器并将所需的“样式”字符串添加到链接:

// helpers/imagebackgoundstyle.js
import Ember from 'ember';
import { imagelink } from 'my-app-name/helpers/imagelink';

export default Ember.Helper.extend({
    compute(params, hash) {
        // ERROR HERE
        let link = imagelink(params, hash);
        return Ember.String.htmlSafe("background-image: url('"+link+"');");
    }
});

像这样称呼seceond助手:

<div style={{imagebackgroundstyle workgroup.imageBackground item='workgroup' type='imageBackground'}}>

我在这里遇到的错误是imagelink.imagelink is not a function 我尝试了几种变体,甚至是奇怪的东西,比如imagelink.compute(params, hash),...... 显然我在导入帮助时做错了什么,但我无法绕过什么......?

我已经尝试/查看了 Ember js use handlebars helper inside a controller?Calling a handlebars block helper from another helper 还有几个.... 没解决/过时。

1 个答案:

答案 0 :(得分:1)

我相信您的is not a function错误都与您的导入语法有关:

import { imagelink } from 'my-app-name/helpers/imagelink';

您正尝试导入不存在的内容,因为imagelink帮助程序是默认导出的。所以你必须使用:

import imagelink from 'my-app-name/helpers/imagelink';

但是您的代码会遇到另一个问题,所以我建议将其更改为:

import Ember from 'ember'

import ImageLink from './image-link'

export default ImageLink.extend({
    compute(params, hash) {
            const val = this._super(params, hash)
      return val + '2'
    }
})

你在这里做的只是扩展其他助手,使用this._super()调用它的计算函数,并使用新助手中的返回值。

这是一个twiddle,其中有一个工作示例。

相关问题