Search code examples
javascriptember.jshandlebars.js

Handling action parameter within a component in Emberjs


Why does my <button> work but the {{delete-toggle}} component gives me an undefined for the message variable?

{{delete-toggle action='deleteMessage' message=message}}

<button {{action 'deleteMessage' message}}>Some Action (param: {{message}}</button>

import Ember from 'ember';

export default Ember.Component.extend({
    tagName: '',
    actions: {
        deleteMessage(message){ 
            console.log(message); 
            return this.sendAction('deleteMessage', message);
        }
    }
});


Solution

  • The {{delete-toggle}} component is triggering the default action with no parameter, but your deleteMessage action handler requires one. The button, on the other hand, is explicitly passing along the parameter in its {{action 'deleteMessage' message}} specifier.

    Why pass the parameters around anyway, since the component already knows the message involved?

    {{delete-toggle action='deleteMessage' message=message}}
    
    export default Ember.Component.extend({
    
        // ATTRIBUTES
        message: null,
    
        // ACTIONS
        actions: {
            deleteMessage(){ 
                var message = this.get('message');
                console.log(message); 
                this.sendAction('deleteMessage', message);
            }
        }
    
    });
    

    You can then write the button a bit more simply as

    <button {{action 'deleteMessage'}}>Some Action (param: {{message}}</button>
    

    BTW, I would not recommend empty tags. Is there some reason you are doing that? Also, I don't think returning a value from an action handler does anything useful.