John
John

Reputation: 41

How to pass event objects as parameters (from handlebars template to an action in a controller)

I am new to ember, thus I would appreciate your assistance. I want to pass an focus-out event (see bold marked text below) from my handlebars template:

{{input type="text" class="form-control" **focus-out= (action "ccFocusLost" event**) }}

To my action in my controller:

   ccFocusLost : function(**event**) {
        alert(event.relatedTarget.tagName);
    },

However, i get an undefined when I do as above. I need a way to obtain the focus-out event in order to find out which element will receive the focus after my main element loses it.

Thanks in advance!

Upvotes: 0

Views: 1550

Answers (3)

John
John

Reputation: 41

It was tricky, but here is the solution. I have the following code:

template (no need to have an event argument):

{{input type="text" class="form-control" **focus-out= (action "ccFocusLost") }}

Controller:

      ccFocusLost : function() {    
            var targetId= event.relatedTarget.id;       
            alert(targetId);
        },

So it seems that handlebars can access the event, without the need of sending it as an argument. In this case if I press a button with id = button1, the alert will display button1.

Upvotes: 1

Two things

  1. If you use focusOut instead of focus-out, the action will automatically include the jQuery event as the argument, no need to specify it in the template.

{{input focusOut=(action "ccFocusLost") }}

  1. In your code, the event is already being passed to your action, it's just that the jQuery event's relatedTarget property is null. This is a jQuery/Javascript event thing, unrelated to Ember. See also here.

There's a lot more information out there on relatedTargets, but it seems it would be better to just use document.activeElement

Upvotes: 0

zureka
zureka

Reputation: 66

You can define the focusOut action handler in your controller and check if the event came from your input field with the class "form-control". E.g.

focusOut(event) {
    /* if event did not come from desired input field, return here */
    /* else call the action as desired to process the focusOut event */
}

Alternatively, you could create a component that wraps your input field so you could define the focusOut event at the component level instead of the controller. This would remove the need to check if the event came from the input field.

For more information on handling events in Ember, here is the section of the Guides that provides more detail: Handling Events

Upvotes: 0

Related Questions