简体   繁体   中英

Pass action name to Handlebars helper that should be in helper output

I am trying to create a FontAwesome handlebars helper that can also add an action to the html output.

The handlebars helper takes color and action as optional parameters:

Em.Handlebars.helper('icon', function (iconName, options) {
    var returnString = '';

    options = options.hash;

    returnString += "<i class='icon-" + Handlebars.Utils.escapeExpression(iconName) + "'";
    returnString += options.color ? " style='color: " + options.color + "'" : "";
    returnString += options.action ? " {{action '" + options.action + "'}}" : "";
    returnString += "></i>";

    return new Handlebars.SafeString(returnString);
});

And here is how I am using it:

{{icon 'angle-right' action='expand'}}

Action in controller looks like this:

actions: {
    expand: function() {
        console.log('expanded!');
    }
}

But it doesn't work... When I click the icon, nothing is logged. Is it not possible for Handlebars helpers to output Handlebars code this way? Is there another way of adding an action to the html output element?

Something like this is where you'd want to use a component instead of a Handlebars helper. (Handlebars helpers are very limited in what they can do.)

App.FontAwesomeIconComponent = Em.Component.extend({
    color: '',
    styleAttribute: function() {
        return 'color:' + this.get('color') + ';';
    }.property('color'),

    icon: '',
    fullIconName: function() {
        return 'icon-' + this.get('icon');
    }.property('icon')
});

Then, for your template:

<i {{bind-attr class='fullIconName' style=styleAttribute}}
    {{action 'iconClicked' on='click'}}>
</i>

Then, you can use it like so:

{{font-awesome-icon icon='angle-right' color='blue' iconClicked=expand}}

This will then call the expand action in your controller when the icon is clicked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM