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

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!

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.

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

Two things
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") }}
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

Related

Event handling in EmberJS components using {{#event}} blocks

I've been working on a UI in Ember and I am having difficulty implementing some of the event handling as described on the documentation here
I have a section of a nav bar I need to highlight on hover. The nav bar is made up of ember-bootstrap components.
{{#bs-navbar type="dark" backgroundColor="primary" as |navbar|}}
{{navbar.toggle}}
<div class="container-fluid" style="padding-left:50px;padding-right:50px; ">
<a class="navbar-brand" href="#"><img style="max-width:250px; margin-top: -12px;margin-bottom: -12px" src="/assets/images/logo_white_3x.png"></a>
{{#navbar.content}}
{{#navbar.nav as |nav|}}
{{#nav.item class="highlight-active"}}
{{#nav.link-to "index"}}LIVE{{/nav.link-to}}
{{/nav.item}}
{{/navbar.nav}}
{{/navbar.content}}
<div class="navbar-nav mr-left">
{{#navbar.content}}
{{#navbar.nav as |nav|}}
{{#nav.dropdown class="{{isHover}}" as |dd|}}
{{#dd.toggle }}Link<span class="caret"></span>{{/dd.toggle}}
{{#dd.menu as |ddm|}}
{{#ddm.item}}{{#ddm.link-to "index"}}Link{{/ddm.link-to}}{{/ddm.item}}
{{#ddm.item}}{{#ddm.link-to "cau.all"}}Link{{/ddm.link-to}}{{/ddm.item}}
{{/dd.menu}}
{{/nav.dropdown}}
{{#nav.item}}
{{#nav.link-to "index"}}Current User: <b>MICKEY MOUSE</b>{{/nav.link-to}}
{{/nav.item}}
{{/navbar.nav}}
{{/navbar.content}}
</div>
</div>
{{/bs-navbar}}
To accomplish this I tried to use one of the block events described n the documentation:
//template
{{#hover}}
<h1>link</h1>
{{/hover}}
//component
export default Component.extend({
hover() {
alert('hovered')
},
actions: {
//actions here
}
});
This produces the following error: hover not found, and the catch-all block handler didn't handle it
I thought it might be because the name of the even must be hyphenated so changed it accordingly. This produced a no component or helper by that name error.
Copying and pasting the same text from the guide produces the same errors which suggests there is something more fundamental I am not understanding.
Can anyone shed any light?
First off, if you need to highlight a navbar on hover, you should be doing this with css.
.someClass:hover: {
//apply highlight style
}
As for what's wrong with what you're doing in general, go back and look at those linked docs again. There's no event that ember handles called hover. What you're looking for is mouseEnter and mouseLeave. Check this twiddle to see an example:
export default Component.extend({
mouseEnter(){
this.set('hovering', true);
},
mouseLeave(){
this.set('hovering', false);
}
});
Where we only show the passed block on hover
Hover here ->
{{#if hovering}}
{{yield}}
{{/if}}
Try use an action for the mouseEnter event, e.g. <div mouseEnter={{action "showCaution"}}>
Another way to preserve native event behaviors and use an action, is
to assign a (closure) action to an inline event handler.
The action is simply a function defined on the actions hash of a component. Since the action is assigned to an inline handler, the function definition can define the event object as its first parameter.
actions: {
showCaution(event){
// Only when assigning the action to an inline handler, the event object
// is passed to the action as the first parameter.
}
}

Ember JS: How can I practice 'Data Down, Actions Up' with composable helpers?

New to ember and practicing 'Data Down, Actions Up' with composable helpers. Is this possible? This is what I'm attempting to do:
//parent template
{{pizza-toppings toggleToppings=(action (toggle 'toppings' this 'mushrooms' 'anchovies'))}}
//child component template
<div {{action "toggleToppings"}}>
But I get a 'no action handler for: toggleToppings' error.
So then I tried making an action on the child, like so:
//child component template
<div {{action "togglePizza"}}>
//child component JS
actions: {
togglePizza() {
this.get('toggleToppings')();
}
}
But when I click on that, nothing happens at all. :( How can I call my parent action from within my component template?
Change the child component template to the following:
<div {{action toggleToppings}}>
When you use quotes, you are telling handlebars to lookup an action by that name on the actions hash of the current context (and bubble that action up if it is not found). However, when you pass an action (an action is really just a bound function) into this component from the parent you don't add it to the actions hash, you've just added it as a property on the component's context.
As for why the latter second attempt did not work for you, I suspect it actually does work but that the action handler has some other non-related issue. Adding a debugger to the "toggle" helper will let you know whether and when it is being called.

Should the Ember hbs template pass in parameters from an input field to a function and if so how?

I have a form that has an input field and an associated button and I have a function that would like to have the value the user types into the input field. Should I be passing it somehow from the hbs template or should I just go and get it from the DOM in the function.
Is there something like this?
{{ action myFunction $("#myInputId").val() }}
Yes you can do this by value property of action as shown below:
<input oninput={{action "myaction" value="target.value"}}/>
Here is an ember-twiddle for you.
Conceptually - you are on the right track.
In this case... here is a route (application route)
import Ember from 'ember';
export default Ember.Route.extend({
alertInput: function(inputValue) {
alert(inputValue);
},
actions: {
doSomething(userInput) { // (this is already a function)
// alert(userInput); // or... use a regular function in the action
this.get('alertInput')(userInput);
},
},
});
and here is a template (application template)
{{input value=userInputProperty}}
<button {{action 'doSomething' userInputProperty}}>doSomething</button>
This action takes a function name - and then a value as a parameter to pass to the function.
There a few ways you might do things depending on what you are trying to do.
https://ember-twiddle.com/3080649ecf98cddef6d3d64b186ba741?openFiles=templates.application.hbs%2C
(good time for a twiddle)
You can bind the value of the input box to a controller property and you can use that property to derive the value of the input box in the button action.
Here is an ember-twiddle for you.
Note: Ember Controllers are SINGLETONS.
Passing the value directly is not possible, but you can bind the value to a property.
I would suggest to wrap the input in a component and bind the input value to a component property.
Then you can pass the value as action parameter or access it directly in the action handler of the component.
This solution avoids a singleton controller and the component could be possibly reused.
See also https://guides.emberjs.com/v2.18.0/templates/actions and https://guides.emberjs.com/v2.18.0/templates/input-helpers.

Now that Ember.View is deprecated, how does one access event objects for events triggered in the top-level application.hbs template?

I am upgrading an application that customizes Ember.View for the top-level application.hbs. There I have an event handler that needs access to the event object that gets passed in:
ApplicationView = Ember.View.extend({
click(event) {
// Need event here.
}
});
Now that Ember.View is deprecated, I'm not sure how to replace this logic.
I could add an action handler at some div that would capture the event of interest in application.hbs:
<div {{action "topLevelClick"}}>
...
</div>
But although this fires, I don't have access to the event object.
Any thoughts on how to handle this?
Actions declared as DOM event handlers do pass the event:
{{!-- application/template.hbs --}}
<div onclick={{action 'topLevelClick'}}>Click Me</div>
// application/controller.js
actions: {
topLevelClick(event) {
console.log('topLevelClick', event);
}
}
This works on Ember 1.13.13; I haven't tried 1.13.11, though it also supports these kinds of event handlers in general.
By default, the action handler receives the first parameter of the event listener, the event object the browser passes to the handler.
Therefore, in your action you can get the event as the first parameter.
Let say in your controller for application, you have action as:
actions: {
topLevelClick: function(event){
console.log(event);
}
}
this will print on the console, the actual browser event.
Hope this helps.

binding context to action in ember textfield

I've got an ember application that needs to manage multiple chat windows. A window for each active chat is created within an {{#each}} loop. This is straightforward enough. The place that I'm having trouble is sending the chat message when the user presses enter.
The window looks like this
{{#each chats}}
... stuff to display already existing chats...
{{view Ember.TextField valueBinding="text" action="sendChat"}}
<button {{action sendChat this}}> Send </button>
{{/each}}
This works fine for the button, since I can pass this to it. By default the function defined in the textfield view action just gets the text within that textfield, which is not enough in this case. Since there can be multiple chat windows open, I need to know which window the message was typed into. Is it possible to pass this to the textfield action function? (or can you suggest a different way to solve this problem?)
Add contentBinding="this" to the definition of the view, like:
{{view Ember.TextField valueBinding="text" action=sendChat contentBinding="this"}}
EDIT
Ember master already has this change, but the official downloadable verstion still don't.. so you will need to subclass the Ember.TextField and change its insertNewline to achieve required functionality:
App.ActionTextField = Em.TextField.extend({
insertNewline: function(event) {
var controller = this.get('controller'),
action = this.get('action');
if (action) {
controller.send(action, this.get('value'), this);
if (!this.get('bubbles')) {
event.stopPropagation();
}
}
}
});
After that, the action handler will receive additional argument, the view:
{{view App.ActionTextField valueBinding="text" action=sendChat myfieldBinding="this"}}
and in controller:
sendChat: function (text, view) {
var myField = view.get('myfield');
//do stuff with my field
}
You may use ember master instead of subclassing Ember.TextField..
I hope the ember guys will release the next version soon..
I know this question has been answered but I said let me add some information that may help out someone in the situation of actions and TextField. One word "Component". TextField in Ember is a Component so if you think of TextField from that perspective it may help when it comes to sending actions and using TextField in an application.
So when you say App.SomeTextField = Ember.TexField.extend({...});App.SomeTextField is subclassing Ember.TextField (remember which is a component). You could add your logic inside and that works and you could access it from your template such as {{view App.SomeTextField}}
You may be thinking I see the word 'view' this guy sucks, TextField is a View. Well, it is sort of a View because Ember Components are a subclass of Ember.View so they have all that Views have. But there are some important things to keep in mind Components un-like Views do not absorb their surrounding context(information/data), they lock out everything and if you want to send something from the outside surrounding context you must explicitly do so.
So to pass things into App.SomeTextField in your template where you have it you would do something like {{view App.SomeTextField value=foo action="sendChat"}} where you are passing in two things value, and action in this case. You may be able to ride the fine line between View/Component for a bit but things come crashing why is your action not sending?
Now this is where things get a little trippy. Remember TextField is a Component which is subclassed from View but a View is not a Component. Since Components are their own encapsulated element when you are trying to do this.get('controller').send('someAction', someParam), "this" is referring to the Component its self, and the controller is once again the component its self in regards to this code. The action that you are hoping will go to the outside surrounding context and your application will not.
In order to fix this you have to follow the protocol for sending actions from a Component. It would be something like
App.SomeTextField = Ember.TextField.extend({
//this will fire when enter is pressed
insertNewline: function() {
//this is how you send actions from components
//we passed sendChat action in
//Your logic......then send...
this.sendAction('sendChat');
}
});
Now in the controller that is associated with where your SomeTextField component/view element is you would do
App.SomeController = Ember.Controller.extend({
//In actions hash capture action sent from SomeTextField component/view element
actions: {
sendChat: function() {
//Your logic well go here...
}
}
});
Now I said to think of TextField as a Component but I have been riding the tail of the view and declaring {{view AppSomeTextField...}}. Lets do it like a component.
So you would have in your template where you want to use it
//inside some template
`{{some-text-field}}`
Then you get a specfic template for the component with the name:
//template associated with component
<script type="text/x-handlebars" data-template-name="components/some-text-field">
Add what you want
</script>
In your JS declare your component:
//important word 'Component' must be at end
App.SomeTextFieldComponent = Ember.TextField.extend({
//same stuff as above example
});
Since we on a role you could probably get the same functionality using Ember input helpers. They are pretty powerful.
{{input action="sendChat" onEvent="enter"}}
Welp hopefully this information will help someone if they get stuck wondering why is my action not sending from this textField.
This jsBin is a sandBox for Components/Views sending actions etc....Nothing too fancy but it may help someone..
http://emberjs.jsbin.com/suwaqobo/3/
Peace, Im off this...