How to access child component from parent component in Ember - ember.js

The concept is fairly simple.
Assume I have a child component with its own separate js and hbs.
Child-component.hbs =>
<Button options = {{listOptions}} selected={{selectedOption}}
> Submit <Button
Child-component.js
listOptions =[{id: 124, name: 'Mywork'}
selected => performing an action after getting the value from hbs selection.
Now I'm importing this into another component Main-component.hbs like this
<ChildComponent />
This is rendering as expected with options and all, but based on the selectedOption I want to do something in my main component. Handling the action in the Main-component is not an option for me as its not what I was told to do. Is it possible to access selectedOption from the main-component? Kindly help.
Please note that I want to achieve this in Octane version.

the only way to do this is to specifically pass a reference from the parent to the child, and have the child invoke some function on the parent (because, in rendering, data only flows down by default ("data down, actions/functions up"))
Example:
class Parent {
foo(child) {
// do something with the child
}
}
<Child #foo={{this.foo}} />
// ------------------
class Child { }
{{ (#foo this) }}
Note that this is an "effect", and effects are generally a code-smell (derived data should be used whenever possible)

Related

How to pass an "action" from a template to it's grand child components in Ember Octane

I am trying to pass an "action" from the controller to the grandchild component of the current template. But it fails for somereason. Could anyone let me know what am I missing here.
MainTemplate's Router Controller
export default class MainTemplateController extends Controller {
field = "userId";
#action
save () {
//save data
}
}
MainTemplate.hbs
<ChildComponent #field={{this.field}} #save={{this.save}} />
ChildComponent.hbs
<GrandChildComponent #field={{this.field}} #save={{this.save}} />
GrandChildComponent.hbs
<button #onClick={{action "doSomething" (readonly #field)}}>Save</button>
export default class GrandChildComponent extends Component {
#action
doSomething(fieldName) {
console.log(fieldName); // logs as "userId"
console.log(this.args.save) // undefined
}
}
Your code looks fine. There is a small #argument issue in your ChildComponent.hbs file.
Since you are passing the argument from the MainTemplate (save and field) to GrandChildComponent via ChildComponent. The GrandChildComponent invocation should be something like,
<!-- ChildComponent.hbs -->
<GrandChildComponent #field={{#field}} #save={{#save}} />
as these two properties are argument to the ChildComponent component and it's not owning them. Hope this solves your issue and this cheat sheet helped me to understand octane better :)

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.

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!
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

How do independent components communicate in ember?

How do I let independent component let know of changes or events in a component?
eg:
<#user-social profile>
{{partial 'user-handle'}}
<div class='subtext'>
{{#reply-component}} {{/reply-component}}
</div>
<div class='replybox hide'>
<textarea></textarea>
<input type='button' value='Reply to user' />
</div>
</user-social profile>
Problem: I want replybox to toggle its visibility when a link inside reply component is clicked.
Components are isolated by design. It’s your responsibility to specify their dependencies. You can introduce communication channels between a parent and child component either by passing bound attributes to the child or specifying actions for the child to trigger on the parent.
Actions are probably a better fit, as using two-way bindings as a form of communication is increasingly considered an anti-pattern. An example:
{{#reply-component toggleReplybox="toggleReplybox"}}
Then, in your child component:
actions: {
whateverTriggersTheToggle: function() {
this.sendAction('toggleReplybox');
}
}
You’d have to add the whateverTriggersTheToggle action to something inside the child component.
In the parent component:
displayReplybox: false,
actions: {
toggleReplybox: function() {
this.set('displayReplybox', !this.get('displayReplybox'));
}
}
This would necessitate adding an {{#if displayReplybox}} wrapper around your replybox element.

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...