【问题标题】:Calling Handlebars helper programmatically in Ember在 Ember 中以编程方式调用 Handlebars 助手
【发布时间】:2014-02-14 00:22:41
【问题描述】:

我的一个组件需要根据提供的参数动态选择 Handlebar 助手。

类似{{dynamic-output value=value helper=helper}}

在组件类中,我想根据提供的帮助器输出值。

我找不到太多关于以编程方式使用 Handlebars 助手的信息 :(

【问题讨论】:

  • 你有多少个不同的参数?你总是可以把这个逻辑嵌套在更多的把手中,比如{{#if hasParameterA}} {{dynamic-output value=value helper=helper}} {{/if}}
  • 我相信你误解了这个问题。我的组件有两个参数“value”和“helper”。组件的输出是应用了帮助器的值。
  • 'helper' 的例子是什么?
  • helper = Handlebars.helper 例如,我有一个助手可以将日期对象转换为漂亮的日期或将数字格式化为美元值。

标签: javascript ember.js handlebars.js


【解决方案1】:

基本上,如果您有一个名为 selectBoxOptions 的助手,则可以在助手中使用以下代码来调用该助手:

return Handlebars.helpers.selectBoxOptions(selectedValue, options);

查看这篇博文了解更多详情:http://www.remwebdevelopment.com/blog/javascript/handlebars-calling-a-helper-function-from-another-helper-231.html

【讨论】:

    【解决方案2】:

    这很容易做到。方法如下:

    helperFunctionOne(value){
        //Fill with the data manipulation you want for "helperOne"
    }
    
    helperFunctionTwo(value){
        //Fill with the data manipulation you want for "helperTwo"
    }
    
    Ember.Handlebars.registerBoundHelper("helperOne", function(value){
        return helperFunctionOne(value);
    });
    
    Ember.Handlebars.registerBoundHelper("helperTwo", function(value){
        return helperFunctionTwo(value);
    });
    
    Ember.Handlebars.registerBoundHelper("helperDynamic", function(value, type){
        if(type == 1){
            return helperFunctionOne(value);
        else if(type == 2){
            return helperFunctionTwo(value);
        }
    });
    

    在上面的代码中,我们设置了 2 个辅助函数和 3 个辅助函数。您现在可以按如下方式调用这些帮助程序:

    {{helperOne someValue}}
    
    {{helperTwo someValue}}
    
    {{helperDynamic someValue someType}}
    

    【讨论】:

    • 这是一个很好的解决方法。但是,我想知道如何调用实际的助手(“helperOne”或“helperTwo”)而不是调用助手正在使用的函数。
    • 那么您实际上是在要求“嵌套”车把助手,而(不幸的是)不支持。
    • 嵌套助手是可能的。见:remwebdevelopment.com/blog/javascript/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多