Propagate action from nested component to AppController - ember.js

I have a component nested several levels down in other components. I'm trying to propagate an action all the way up to the AppController in order to open a modal.
The only way I know of doing this is to pass in the action to each component - but this seems extremely impractical. Is there a better way to access the AppController from a nested component?
See my jsbin for the code
App.IndexRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'blue'];
}
});
App.AppController = Ember.Controller.extend({
actions: {
openModal: function(){
alert('this would open the modal')
}
}
})
App.MainComponentComponent = Ember.Component.extend({})
App.SubComponentComponent = Ember.Component.extend({
actions: {
triggerModal: function(){
// need to trigger the openModal action on the AppController
this.sendAction('openModal')
}
}
})
.
<script type="text/x-handlebars" data-template-name="index">
<h1>Index</h1>
{{main-component model=model}}
</script>
<script type="text/x-handlebars" data-template-name="components/main-component">
<h2>Main component</h2>
{{#each color in model}}
{{sub-component color=color}}
{{/each}}
</script>
<script type="text/x-handlebars" data-template-name="components/sub-component">
<button {{action "triggerModal"}}>{{color}}</button>
</script>
EDIT: I'm aware that I can render a template into the modal outlet:
this.render(modalName, {
into: 'application',
outlet: 'modal'
});
But I'm trying to access an action on the AppController.

You can utilize Ember.Instrumentation module, which can be used like a pub/sub.
Here is a working JS Bin example.
Solution outline:
1. On ApplicationController init, the controller subscribes to "openModal" event.
2. The neseted component instruments the event "openModal" within an action.
3. The instrumentation can be executed with a payload, so this would be the place to determine the modal content.
App.ApplicationController = Ember.Controller.extend({
actions: {
openModal: function(options) {
alert('this would open the modal with the content: ' + options.modalContent);
}
},
subscribeEvents: function() {
this.set('openModalSubscriber', Ember.Instrumentation.subscribe('openModal', {
before: Ember.K,
after: Ember.run.bind(this, function(name, timestamp, payload, beforeRet) {
this.send('openModal', payload);
}),
}, this));
}.on('init')
});
App.SubComponentComponent = Ember.Component.extend({
actions: {
triggerModal: function() {
Ember.Instrumentation.instrument('openModal.sub-component', {
modalContent: 'Inner content of modal'
}, Ember.K, this);
}
}
});

Components are supposed to be pretty isolated, therefore it probably doesn't make sense to be jumping over other components, going straight to their controllers... See the following discussion here
There is a targetObject property, which might be of use to you, although I am not 100% sure what you would set it to in this case.

Related

Re-render view with component after destroy in Ember.js

So I have this issue where Ember will not render my view more than once, even after I have destroyed it.
The code I have, works without using components, so it is probably some issue with the actual view not being destroyed properly.
I render into an outlet in my ApplicationRoute
App.ApplicationRoute = Em.Route.extend({
actions: {
showModal: function() {
// This does not work the second time:
this.render('modal', {
into: 'application',
outlet: 'modal'
});
}
}
});
I set up an event listener for when the Bootstrap modal is hidden
App.BaseModalComponent = Em.Component.extend({
afterRenderEvent: function() {
var self = this;
this.$('.modal')
.on('hidden.bs.modal', function(){
// I am destroying the component,
// when the modal is hidden
self.destroy();
})
.modal();
}
});
The afterRenderEvent is a listener I have attached to the view's afterRender event.
See here for markup, etc.: http://emberjs.jsbin.com/wolicutiwiro/1/edit
A working example without using components: http://emberjs.jsbin.com/lodamojikaqo/1/edit
Check this JSBin It does what you want.
App.ApplicationRoute = Em.Route.extend({
actions: {
showModal: function() {
// This does not work the second time:
this.render('modal', {
into: 'application',
outlet: 'modal'
});
},
closeModal: function() {
console.log("closing modal");
return this.disconnectOutlet({
outlet: 'modal',
parentView: 'application'
});
}
}
});
I believe the main challenge is that I cannot call a closeModal action
from a button in my modal view. Bootstrap itself handles hiding the
modal, but I need to disconnect the outlet to allow the same or
another modal to render.
In order to call this action from your component, you have to send the action from the component to the controller current templates controller:
App.BaseModalComponent = Em.Component.extend({
afterRenderEvent: function() {
var self = this;
this.$('.modal')
.on('hidden.bs.modal', function(){
self.sendAction('action');
})
.modal();
},
});
And when you use your component, make sure to assign the action name:
<script type="text/x-handlebars" data-template-name="modal">
{{#base-modal action='closeModal'}}
<p>One fine body…</p>
{{/base-modal}}
</script>
The action will bubble from the controller to the route. This solution allows you to use bootstrap exactly as is, but I find that the solution Code Jack suggested to be much more Ember.

itemControllers and custom Views

I am working on a small app that animates different iframes in and out of view. Right now I am just trying to start simple with two iframes for my data.
App = Ember.Application.create();
App.IndexRoute = Ember.Route.extend({
model: function() {
return [
{current: true, url:'http://www.flickr.com'},
{url:'http://bing.com'}
];
}
});
App.IndexController = Ember.ArrayController.extend({
itemController: 'iframe',
now: function() {
return this.filterBy('isCurrent').get('firstObject');
}.property('#each.isCurrent')
});
App.IframeController = Ember.ObjectController.extend({
isCurrent: Ember.computed.alias('current')
});
App.IframeView = Ember.View.extend({
classNameBindings: [':slide', 'isCurrent'],
templateName: 'iframe'
});
And my templates:
<script type="text/x-handlebars" data-template-name="index">
<button {{action "next"}}>Next</button>
{{#each}}
{{view "iframe"}}
{{/each}}
</script>
<script type="text/x-handlebars" data-template-name="iframe">
<iframe {{bind-attr src=url}}></iframe>
</script>
Why can't my IframeView access my isCurrent property of my itemController? I am also unsure if this is the right way to do this, or if there is an easier way to have my each use my IframeView
Here is a jsbin: http://emberjs.jsbin.com/vagewavu/4/edit
isCurrent lives on the controller. The controller property will be in scope in the view, but the properties under the controller aren't in scope of the view. You just need to reference controller first.
App.IframeView = Ember.View.extend({
classNameBindings: [':slide', 'controller.isCurrent'],
templateName: 'iframe'
});
Additionally your next action isn't doing anything, just creating some local variables, maybe you weren't finished implementing it. Either way I tossed together an implementation.
next: function() {
var now = this.get('now'),
nowIdx = this.indexOf(now),
nextIdx = (nowIdx + 1) % this.get('length'),
next = this.objectAt(nextIdx);
now.toggleProperty('current');
next.toggleProperty('current');
}
http://emberjs.jsbin.com/vagewavu/10/edit

Ember.js and Foundation 4 modal window

I have two problems with Foundation Reveal and Ember.js.
First, action "close" is not firing. I have any ideas why.
#application.js
App.ModalView = Ember.View.extend({
templateName: "modal",
title: "",
classNames: ["reveal-modal"],
didInsertElement: function () {
this.$().foundation('reveal', 'open');
},
actions: {
close: function () {
console.log('close action fired');
this.destroy();
}
},
});
App.ApplicationRoute = Ember.Route.extend({
actions: {
showModal: function () {
var view = this.container.lookup('view:modal', {title:'Test title'}).append();
}
}
});
#index.html
<script type="text/x-handlebars" data-template-name="test">
<a {{action showModal}}>show modal</a>
</script>
<script type="text/x-handlebars" data-template-name="modal">
<h2> {{title}}</h2>
<p>Im a cool paragraph that lives inside of an even cooler modal. Wins</p>
<a class="close-reveal-modal" {{action close target="view"}}>×</a>
<a {{action close target=view}}>Close</a>
</script>
And the second is that i cant set attributes of view while adding it this way:
App.ApplicationRoute = Ember.Route.extend({
actions: {
showModal: function () {
var view = this.container.lookup('view:modal', {title:'Test title'}).append(); //not setting title
}
}
});
For second i can't find in documentation how i can set view parameters while adding via lookup.
Fiddle: http://jsfiddle.net/L4m6v/
Ember doesn't set up the plumbing when you create a view in this manner.
You can build a popup that lives on the application (which is easy to edit and manipulate from anywhere within the application (controllerFor('application') from a route, or needs:['application'] and this.get('controllers.application') from controllers).
Here's a simple JSBin showing this (I didn't spend much time on making it pretty, CSS isn't really a strong suit of mine anyway).
http://emberjs.jsbin.com/eGIZaxI/1/edit
App.ApplicationController = Ember.ObjectController.extend({
title: "Popup Title",
description: "You should do something",
isVisible: true
});
App.ApplicationRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'blue'];
},
actions: {
hidePopup: function(){
$(".popup").fadeOut();
this.controllerFor('application').set('isVisible', false);
},
showPopup: function(){
$(".popup").fadeIn();
this.controllerFor('application').set('isVisible', true);
}
}
});
I've created project on github for this problem with fixed foundation.reveal.js:
(i didnt find the way to fix foundation.js on jsbin)
I think other libs that making modal have the same problem, so if you'are using jquery-ui you may fix it too.
https://github.com/xjok3rx/ember-modal

Ember.js: when using {{action}}, how to target a specific controller?

I put my question in a code example here:
http://jsbin.com/urukil/12/edit
See, I can use a {{action}} (which is placed in a child view) with target option to trigger an event in ApplicationView or ApplicationController or ChildView, only except the ChildController which is the one I truly wanted.
According the document, if no target specified, the event itself should handled in corresponding controller, in my case, which is should be ChildController. But why this action always lookup in ApplicationController? Did I miss something obviously important?
You can use needs to call a action on different controller...
App.ApplicationController = Ember.Controller.extend({
needs: ['child'],
doSomething: function() {
alert("From ApplicationController");
}
});
And the target can be specified as "controllers.child" from the template
<p {{action doSomething target="controllers.child"}}>Blah blah</p>
Here is your working fiddle...
http://jsbin.com/agusen/1/edit
Use this.controllerFor('') to call different controller event. A working example is given below.
JS:
/// <reference path="Lib/ember.js" />
var app = Ember.Application.create()
app.Router.map(function () {
this.resource('post')
});
app.ApplicationRoute = Ember.Route.extend({
model: function () {
return { "firstName": "amit", "lastName": "pandey" }
}
});
app.ApplicationController = Ember.ObjectController.extend({
Address: "House no 93-B",
fullName: function () {
return this.get("model.firstName") + " " + this.get("model.lastName")
}.property("model.firstName", "model.lastName"),
actions: {
submit: function (name) {
this.controllerFor('post').send('handleclick')
},
makeMeUpper:function()
{
alert('calling application controller Event');
this.set("model.firstName",this.get("model.firstName").toUpperCase())
}
}
});
app.PostRoute = Ember.Route.extend({
model:function()
{
return user;
}
});
app.PostController = Ember.ObjectController.extend({
Hello: "afa",
handleclick: function ()
{
alert('calling post controller Event');
this.controllerFor('application').send('makeMeUpper');
}
});
var user = [
{
id: "1",
Name: "sushil "
},
{
id: "2",
Name: "amit"
}
];
//hbs
<script type="text/x-handlebars">
<button {{action submit firstName}}>CLICK HERE TO CALL Post controller event</button>
{{input type="text" action= "makeMeUpper" value=firstName }}
{{#if check}}
No Record Exist
{{else}}
{{firstName}}{{lastName}}
{{/if}}
{{#linkTo 'post'}}click {{/linkTo}}
{{outlet}}
</script>
<script type="text/x-handlebars" id="post">
<button {{action hanleclick}}>Click here to call application controller event</button>
</script>
As far as I know the view class does not change the current controller. Since you are calling the view from the Application template, it remains in the ApplicationController.
Emberjs.com guides on render:
{{render}} does several things:
When no model is provided it gets the singleton instance of the corresponding controller
Simply changing your code from a view to a render call seems to do the trick:
Trigger ApplicationController
</p>
{{render 'child'}}
Since controllerFor is getting deprecated, the correct way to do this now is to specify needs in the controller, retrieve it from the controllers list, and then send it there. Example:
App.SomeController = Em.Controller.extend({
needs: ['other'],
actions: {
sayHello: function () {
console.log("Hello from inside SomeController.");
this.get('controllers.other').send('helloAgain');
}
}
});
App.OtherController = Em.Controller.extend({
actions: {
helloAgain: function () {
console.log("Hello again from inside OtherController!");
}
}
});
EDIT: oops... Looks like someone already posted this answer in essence. Will revise if needed.

createRecord called w/o params does not add object to collection

Using:
ember-1.0.0-pre.4.js
ember-data.js REVISION:11
handlebars-1.0.rc.2.js
Please have a look at this jsFiddle illustrating the described problem.
I have a list of items that are displayed in a template. The template contain a linkTo helper that let's the controller add an item to the collection and is shown as a text input on the page.
Adding the item to the collection is done by the controller:
App.TodoItem = DS.Model.extend({
title: DS.attr('string', { defaultValue: "unknown" })
});
App.Router.map(function () {
this.resource('todo_items')
});
App.TodoItemsRoute = Em.Route.extend({
model: function () {
return App.TodoItem.find();
}
});
App.TodoItemsController = Em.ArrayController.extend({
addTodoItem: function () {
App.TodoItem.createRecord();
}
});
If I want the new item to be shown is the list, I have to pass params to createRecord, otherwise the item is not visible. The same behaviour can be reproduced by using Chrome's inspector and then the item can be made visible as follows:
// Open the jsFiddle http://jsfiddle.net/bazzel/BkFYd/ and select 'result(fiddle.jshell.net) in the inspector, then:
var item = App.TodoItem.createRecord();
// Nothing visible yet.
item.set('title', 'Whatever');
// Now the text input appear with the title as its value.
Is this expected behaviour and if so, what am I missing here?
I took time to redo your example the way i feel things should be done properly with Emberjs. You should rather make sure of transaction and properly define your views and then all your issues get taken care of. So here's how i think you should do this
Define a view for the textfield to capture the value being entered or
just bind it to the model property.
Listing items and adding a new item to the list should be done in two different views and should not be mixed together
<script type="text/x-handlebars">
{{outlet}}
<div>
{{outlet 'addItem'}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="todo_items">
{{#linkTo 'todo_items.new'}}Add Todo Item{{/linkTo}}
<ul>
{{#each item in controller}}
<li>
{{#unless item.isNew}}
{{item.title}}
{{/unless}}
</li>
{{/each}}
</ul>
</script>
Define different states for listing items and adding a new one
To benefit from automatic binding of your text field value to the
model property, you need to associate an ObjectController to the TodoItemsNew route
Finally, make use of transaction to create and commit records to the store
window.App = Em.Application.create();
App.TodoItem = DS.Model.extend({
title: DS.attr('string')
});
App.TodoItem.FIXTURES = [{
id: 1,
title: 'Lorem'
}, {
id: 2,
title: 'Ipsum'
}];
App.store = DS.Store.create({
revision: 11,
adapter: DS.FixtureAdapter.create()
});
App.Router.map(function () {
this.resource('todo_items',function(){
this.route('new');
})
});
App.IndexRoute = Em.Route.extend({
redirect: function () {
this.transitionTo('todo_items');
}
});
App.TodoItemsRoute = Em.Route.extend({
model: function () {
return App.TodoItem.find();
}
});
App.TodoItemsNewRoute = Em.Route.extend({
transaction: App.store.transaction(),
setupController:function(controller) {
console.info(controller.toString());
controller.set('content',this.transaction.createRecord(App.TodoItem));
},
renderTemplate: function() {
this.render('addItem',{
into:'application',
outlet:'addItem',
})
},
events: {
addItem: function() {
this.transaction.commit();
this.transitionTo('todo_items');
}
}
});
App.TodoItemsController = Em.ArrayController.extend();
App.TodoItemsNewController = Em.ObjectController.extend();
App.TextField = Ember.TextField.extend({
insertNewline: function () {
this.get('controller').send('addItem')
}
});
Here' is a working version of the example on jsfiddle. Hopefully, i helped with this example clarify some of your issues.
Thank you Ken for answering my question. It indeed feels like a more proper of way of doing this in Ember. However, I still think it's difficult to get the hang of which objects are accessible from where...
Your example inspired me to do a rewrite of my code. I also made some changes to your approach:
I'm not sure if it's the best practice, my I don't create a store instance. Instead I define a Store class.
The content for the TodoItemsNewController is set by calling the model property on the corresponding route.
renderTemplate in the TodoItemsNewRoute only needs the outlet key.
<script type="text/x-handlebars">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="todo_items">
{{#linkTo 'todo_items.new'}}Add Todo Item{{/linkTo}}
<ul>
{{outlet "addItem"}}
{{#each controller}}
<li>
{{#unless isNew}}
{{title}}
{{/unless}}
</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars" data-template-name="todo_items/new">
{{view Ember.TextField valueBinding="title" placeholder="Enter title"}}
window.App = Em.Application.create();
App.TodoItem = DS.Model.extend({
title: DS.attr('string', {
defaultValue: "unknown"
})
});
App.TodoItem.FIXTURES = [{
id: 1,
title: 'Lorem'
}, {
id: 2,
title: 'Ipsum'
}];
App.Store = DS.Store.extend({
revision: 11,
adapter: DS.FixtureAdapter.create()
});
App.Router.map(function() {
this.resource('todo_items', function() {
this.route('new');
});
});
App.IndexRoute = Em.Route.extend({
redirect: function() {
this.transitionTo('todo_items');
}
});
App.TodoItemsRoute = Em.Route.extend({
model: function() {
return App.TodoItem.find();
}
});
App.TodoItemsNewRoute = Em.Route.extend({
model: function() {
return App.TodoItem.createRecord();
},
renderTemplate: function() {
this.render({
outlet: 'addItem'
});
}
});
App.TodoItemsNewView = Em.View.extend({
tagName: 'li'
});
The updated example is on jsFiddle.
Any reviews are welcome.