binding controller object to a component in ember - ember.js

I am trying to build a modal box component in ember. The modal box has two standard buttons, "close" and "save". I wanted to pass controller action to this component so that when save button is clicked, it calls the controller action that was passed. I call my component as :
{{#affi-modal-box title="Test title" modalId="createNewAnalyticsRunModal" controllerBinding=controller}}some message{{/affi-modal-box}}
and my component :
AS.AffiModalBoxComponent = Ember.Component.extend({
attributeBindings: ['modelId','test'],
//this is the function that gets called when save button is clicked
onSaveButtonClick : function(){
console.log(this.controllerFor('analysisTemplates'));//fails
console.log(this.get('controller'));//returns modal box component which I don't need
}
});
Any ideas how I can pass the controller object to the component??
Thanks.

The way Ember.Component's work is to be agnostic to other parts of your application, therefore rather then passing in a controller on which you want an action to be called on when something happens in your component, you do it more like in this way:
{{#affi-modal-box
title="Test title"
modalId="createNewAnalyticsRunModal"
action="actionNameOnTheController"}}some message{{/affi-modal-box}}
As you can see you set the action attribute to the action name on your controller, and then inside your component you simply call this.sendAction('action'); which will trigger whatever action name you defined earlier:
AS.AffiModalBoxComponent = Ember.Component.extend({
attributeBindings: ['modelId','test'],
//this is the function that gets called when save button is clicked
onSaveButtonClick : function(){
this.sendAction('action');
}
});
So now, whenever onSaveButtonClick is invoked it will send the action actionNameOnTheController to whatever controller is listening to it. And best of all, without knowing nothing about the controller. This is the kind of functionality that makes Ember.Component's reusable in any way.
Please see here a simple demo of the concept explained.
Hope it helps.

Related

EmberJS - Rendering separate route as a modal into a specific outlet

In my EmberJS applications I have two separates routes as follows,
Route A - "main/books/add"
Route B - "main/authors/add"
I have an "Add Authors" button In Route A template and when a user presses that button I want to load and render Route B in a modal to add new authors.
I know its possible to achieve somewhat smiler to this by using the route's render method to render the Route B template and respective controller.
But in that case, the "model" hook of Route B in "main/authors/add.js" file does not get invoked.
It would be really nice if someone can suggest me a method to render a separate route into a modal.
EDIT - Although this is entirely valid (the premise of rendering into using named outlets, views are now deprecated in Ember 1.1. The same can be achieved by using a Component
Yup, you can do this:
What you'd want to do is create a modal in a template and assign a named outlet into it (or create a view that is a modal with an outlet):
in modal.hbs:
<div class='modal'>
{{outlet "modalContent"}}
</div>
Then I would override your base button like so:
App.BasicButton = Em.View.extend({
context: null,
template: Em.Handlebars.compile('<button>Click Me!</button>');
click: function(evt) {
this.get('controller').send('reroute', this.get('context'));
}
});
And in your template set up your button to trigger your modal:
in trigger.hbs
<!-- content and buttons for doing stuff -->
{{View App.BasicButton context='modalContent'}}
Finally, you want to create a method in your route which handles rendering specific content into your outlet:
App.TriggerRoute = Em.Route.extend({
actions: {
reroute: function(route) {
this.render(route, {into: 'modal', outlet: route});
}
}
});
So in essence, you're rendering the template (called "modalContent") into a specific outlet (called "modalContent"), housed within the template/view (called "modal")
You would also want to write some logic to trigger the modal to open on element insertion. To do that, I would use the didInsertElement action in the modal view:
App.ModalView = Em.View.extend({
didInsertElement: function() {
this.$.css("display", "block");
//whatever other properties you need to set to get the modal to pop up
}
});

Ember.Component's sendAction() to view target

sendAction() in an Ember.Component bubbles to controller by default which is expected. But i have 2,3 actions which i rather need to send to corresponding view which is using the component. In templates we set action to view using target=view. Can we do that?.
Update: Currently as a work around I am sending my view object to component which from there calls view.send() to send the action. But i feel this is not correct.
Ok after some thinking I believe i know that you mean. If you have a component and you have a action it will be handled by the component itself. If you want to send a action outside the component you would use sendAction.
Now to target the view of which holds your component since your component is base on a view, you can probably do this.get('parentView') to get the parent view and then chain send('nameOfAction')
So it would be this.get('parentView').send('nameOfAction') from within the component action and it will then trigger the action on the parent view of which the component is embedded.
So in your component you could have:
App.DemoCompComponent = Ember.Component.extend({
actions: {
internalTrigger: function() {
//just an alert to make sure it fired
alert('Internal action was caught on component');
//this should target parent view component is in
this.get('parentView').send('viewTriggerTest');
}
}
});
Now lets say you have you component in the index template you could:
The template would be:
<script type="text/x-handlebars" data-template-name="index">
<h2>Inside Index Template</h2>
{{demo-comp}}
</script>
The Index View Code would be:
App.IndexView = Ember.View.extend({
actions: {
viewTriggerTest: function() {
alert('View Trigger Test Worked on Index!');
}
}
});
Here is a jsbin
http://emberjs.jsbin.com/reyexuko/1/edit
For latest Ember 2.9 the recommended approach is to pass a closure action to the child component. The property target and parentView are private ones.

How do I bind a controller to the view when the controller is create by Ember.js

this question is slightly related to How to display the “content” of an ObjectController?
However, in the provided solution and all other examples I can find the controllers are always created explicitly. The nice thing about Ember.js is that the Route takes care of mostly everything. So I don't want to create the controller but want to bind it to a view:
{{view App.myview controllerBinding="App.applicationController"}}
You can see the complete example in this fiddle. The example is not that great because Ember usually sets the controller of a child view to its parent view.
In the end I need to know, how I can access a controller which is created by Ember from a view.
Thanks for any help!
Update:
I provided the wrong fiddle or it did not save my changes. Here is the link to the right version: http://jsfiddle.net/ncaZz/1/
What should I provide in line 9 in the templates?
From the view you can access the controller with
this.controller
If you need other controllers than your view controller you can use the needs in the viewcontroller:
App.DatasetEditController = Ember.ObjectController.extend({
needs: ['mappingIndex']
});
and then use:
this.controller.mappingIndex
You don't really need to bind to it. You can access the controller from the view by calling it like this.
this.get('controller');
Updated Answer:
You really should not have your click event inside your view. Your actions should either be in your controller or your router.
Your template should become
<span style="background-color: green" {{action doStuff}}>
Click
</span>
and you should have a controller that should have this
App.MyController = Em.Controller.extend({
needs: ['application'],
doStuff: function(){
this.get('controllers.application').foo();
}
});
Also, the MyView and MyController should be capitalized, because when extending these items from ember that are not instances, and the capitalization is required. The view should only really have stuff in the didInsertElement that handles special things like any kind of jquery animations or initializing a date picker. But, the "ember way" is to have action in the router or controller.

ember-pre4 action helper does not pass browser event anymore?

Hi i have the following code in my template:
<div {{action "play" this target="view"}}>{{title}}</div>
and the following code in my view:
MB3.PlaylistView = Ember.View.extend({
play: function(event) {
}
});
the parameter event passed to the play function is now the playlist model (passed as "this" in the action helper shown above)
In Ember-pre2 the parameter passed to the action handler recieved the browser event with attributes like currentTarget etc. and a property context where the model was in.
How can i access the native event's parameters like currentTarget in ember-pre4?
There is a lot of discussion on this ticket as well:
https://github.com/emberjs/ember.js/issues/1684
The recommended solution would be to create a custom view and then define a click handler. The click handler will be passed the event as the first argument.
MB3.PlayButtonView = Em.View.extend({
click: function(event){
... click handler
}
});
this is by intention but there is an improvment issue for that, see https://github.com/emberjs/ember.js/issues/1986

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