Ember 2.5 Application Controller not present? - ember.js

This is a very simple and probably easily resolved one.
I have created an emberjs application controller via ember generate controller application from which I want to return some basic computed properties based on the current path to higher level controllers and components. Basically, something like this:
export default Ember.Controller.extend({
entity: Ember.computed('currentPath', () => {
return this.get('currentPath').split('.')[0];
})
});
Oddly enough, I cannot access these computed properties anywhere (they turn out undefined, even if I replace them with a debug string), and in the Ember Inspector's view tree, the application controller is apparently not even present:
I have an older Ember 1.13.0 app, where I'm using the application controller with no difficulty. Have I missed a deprecation here? Or do I need to register the application controller in a specific location?

okay, I solved this differently using injection of the routing service directly into the component (see Component to be notified on route change in EmberJS 2 for details)

Related

Combining two emberjs apps

I am currently using ember 1.13. I have two apps which use emberjs. Now I am thinking of integrating these two apps by creating a new route in the first app and display specific route of the second app. Many suggested to use ember-engines,but they need ember 2.10 or higher.Since my application mostly depends on IE 8,I cannot migrate from ember 1.x.
So what should I do? Thanks in advance!!
Cheers!!!
So one approach that would work pre engines is to leverage an addon for the common routes. Your addon will define routes, controllers, and templates as usual with the addons directory. You will also want to define something like addons/utils/router-utils:
// assume we have a single route foo
export function addRoutes(router) {
router.route('foo');
}
router is the this value that ember provides when invoking Router.map. So, within your addon, to allow for "normal" feeling development, you'll want to use this addRoutes function within the dummy app router in tests/dummy/app/router.js:
import EmberRouter from '#ember/routing/router';
import config from './config/environment';
import { addRoutes } from 'addon-with-routes/utils/router-utils';
const Router = EmberRouter.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
addRoutes(this);
});
export default Router;
Note well, the above router.js file is what Ember 3.8 generates. Yours will most likely differ but the key point is that we invoke our addRoutes function with the anonymous Router.map this value to dynamically add our routes to the dummy app. See this twiddle for an example of adding routes to the router dynamically.
You can now run ember serve from within the addon project and test your routes. Acceptance tests run against the dummy app as well so you're not really constrained by this approach.
Now within your consuming app, you would do the same thing we did in the dummy app to add the routes. This approach, in general, though will require careful engineering to work effectively (a lot of the problems that ember engines solves must be solved by you in some way). Your addon will most likely have to expose a lot of configuration so that you can route outwards from the addon back into the consuming app which will not know about the routes in the consuming app. You'll have to avoid namespace collisions. Sounds fun though :)

Elesticsearch and Emberjs

I'm trying to wire EmberJS with ElasticSearch. So far, I've read most of the Ember documentation, and found out this adapter for ElasticSearch.
The problem is I can't figure out how to use it (i.e. configure it so that when I call store.save(), my model is sent to ES.
What I have ATM is a newly created project with Ember generator (ember new ), and a generated controller, router, model, etc. My problem is that the Ember document explains how to customise adapters, but not how to use them (or I missed that part). The ES adapter's documentation says :
var App = Em.Application.create();
App.store = DS.Store.create({
revision: 4,
adapter: DS.ElasticSearchAdapter.create({url: 'http://localhost:9200'})
});
which implies to create a Store, whereas I can only see ways to extend it in the Ember documentation. Furthermore, I already have a Store in my application.
So the questions are:
do I need to override the store creation to replace it with the ES one (and where to do that) OR
do I need to extend the existing one, and in this case, how should I do that ?
Also, when it says:
First, load the ember-data/lib/adapters/elasticsearch_adapter.js file
in your application.
where and how that should be done ?
On your first questions/s
do I need to override the store creation to replace it with the ES one
(and where to do that) OR do I need to extend the existing one, and in
this case, how should I do that ?
You're onto the right track in the second part, you will need extend the existing one, but not the store, the adapter in this case.
So if you're using ember-cli, which according to this:
What I have ATM is a newly created project with Ember generator (ember
new )
It seems that you are and so you'll application folder structure should be like this:
app ->
adapters(you need to generate/create this)
components
controllers
models
routes
serializers
services
styles
templates
And now we can answer:
how should I do that ?
If you do not have the adapters folder yet, which you probably don't, just run ember generate adapter application or create a folder adapters, and a file application.js for that folder.
And that then finally leads us to a part of your last question.
load the ember-data/lib/adapters/elasticsearch_adapter.js file in your
application. where and how that should be done ?
import ElasticSearchAdapter from 'ember-data/lib/adapters/elasticsearch_adapter'
export default ElasticSearchAdapter.extend({
})
Now the possible bad news, that adapter is likely very outdated, as it the repository's last commit was 27 Dec 2012.

How do you update a controller from another controller in ember.js?

In my application I have common header that outlets into the main application layout. In that header you can select a site. I need that site selection to update another template that is rendered in the application layout. Having struggled with this for a few days I think the correct way to solve this is to use a shared service, to have the header controller observe the site selection and set that value in the shared service, then to have the index controller use a Ember.computed.alias on the value in the service controller. The following is an example of my code:
controllers/header.js
import Ember from 'ember';
export default Ember.Controller.extend({
sessionService: Ember.inject.service(),
currentSiteChanged: Ember.observer('session.current_site', function(){
var current_site = this.get('session.current_site');
console.log('currentSiteObserver', current_site);
this.get('sessionService').set('currentSite', current_site);
}),
});
controllers/index.js
import Ember from 'ember';
export default Ember.Controller.extend({
sessionService: Ember.inject.service(),
currentSite: Ember.computed.alias('sessionService.currentSite'),
dashboardData: function(){
var currentSite = this.get('currentSite');
console.log("in dashboardData", currentSite);
//other code that uses the currentSite
}.property('currentSite'),
});
services/session-service.js
import Ember from 'ember';
export default Ember.Service.extend({
currentSite: null,
setCurrentSite: function(){
var currentSite = this.get('session.current_site');
this.set('currentSite', currentSite );
}.on('init'),
});
I think this should allow someone to select a site in the header and have the dashboardData property in index update to use that selection. When the page initially loads the header defaults to the first site and the index renders it has the correct site value that it must have gotten from the session-service, however if you select another site the index does not get updated. Via the console.logs and debugging I can see that the header is observing the change and setting the value on the session-service.
Additionally I have tried solving this other ways (injecting the header service into the index and observing a property, injecting the index in the header and directly setting the value, sending and listening to events,etc) but I am willing to try anything or to be corrected that this isn't the correct way to solve the problem.
I am using ember 1.13.8 and moving to 2 isn't an option at the moment.
I don't think a service is an appropriate solution to this problem.
You want your application to have a good RESTful url design (respect for urls is a corner-stone of the Ember framework), so try to capture your application state in the URL.
Consider that if a user were to select a site, and then hit refresh they would lose their selection unless you stored it somehow in a cookie or localStorage.
I would recommend using either routes or query parameters to solve your problem.
Routes
Using routes is fairly straightforward (http://whatever.com/sites/pet-hampsters).
Query Params
You can also use query params, something like this http://whatever.com/?site=pet%20hampsters.
To do this you would write an action that bubbles up to your application controller and sets the value of the 'site' queryParam. Any of your sub-controllers on the currently active route can then read the site value with the new Ember.inject syntax. This is the conventional way to manage dependencies between controllers.

How to create a controller property that updates when a service property changes

Using Ember 1.13
I may be missing something and going about this in the totally wrong way.
I have session state saved in an ember service that is available to all my controllers. It has a boolean property isExistingSession.
In the header of my app I want to conditionally display a login button or user info depending on the value of isExistingSession.
As far as I know I can't use the service property directly in my handlebar so my solution was to create a computed property on the applicationController that always equals the value of of isExistingSession on the sessionService
export default Ember.Controller.extend({
isExistingSession: function () {
return sessionService.get('isExistingSession');
}.property('sessionService.isExistingSession'),
But the computing the property off of an outside entity seems to be invalid.
Any idea on how to accomplish this?
As far as I know I can't use the service property directly in my handlebar
Just to clarify: any property available in a given controller will be available in its associated template. So if you inject your session service in your application controller you should be able to use any property of that service in your application.hbs template.
Now to solve your issue: how do you inject the service in your controller? You have 2 alternatives:
application.inject('controller', 'sessionService', 'service:session'); This will inject your session service in all the controllers, making in available to all your templates as well. (see http://guides.emberjs.com/v1.10.0/understanding-ember/dependency-injection-and-service-lookup/)
sessionService: Ember.inject.service('session'), This will inject your session service in a single controller (see http://emberjs.com/api/classes/Ember.inject.html#method_service)
Bottom line is that you should not need a computed property. I'd recommend using the Ember inspector to check whether your session is properly injected in your controller.
Also, consider using ember-simple-auth, an awesome add-on to manage authentication in Ember.

ember-cli & common route and controller behavior options: Subclass, Mixin or initializer (service)?

I have properties and methods I want exposed to most/all instances of a class (i.e. all but a handful of routes, controllers, whatever). There seems to be multiple ways to accomplish this and I'm looking for guidance for best practices here.
More specifically, I've created a property on my application controller to hold a user session object. I want all other controllers to expose this data as if I had typed:
needs: ['application'],
userSession: Ember.computed.alias('controllers.application.userSession')
directly into the controller.
Further, I want to override all routes (other than the login route and maybe a couple more) implementations of beforeModel to check for the presence of userSession and redirect to the login route if absent.
This is being implemented in ember-cli FYI. So, that being the case, what's the "right" approach here? Do I try to inject these changes via initializers/services? Do I create mix-ins to do this stuff (I'm not a fan of having to remember to do that every time someone working on this does ember g controller that they then have to remember to add the mixin).
Sounds very much like the use of an initializer and a service is the best approach (them being split up makes for cleaner code). The initializer is just the code to load the service, the service does the hard work. The initializer should look something like:
import AuthService from '../services/auth';
export default {
name: 'auth-service',
initialize: function( container, app ) {
app.register( 'service:auth', AuthService, { singleton: true } );
app.inject( 'controller', 'auth', 'service:auth' );
app.inject( 'route', 'auth', 'service:auth' );
}
};
This then injects auth into every controller and route, and you should move the userSession from your application to the service.
My auth service is too big (and in my case: too specific, as it uses Firebase) to be quoting it here. I gave the gist of it in an answer yesterday: Short delay when trying to run redirect with ember route with firebase authentication
And as you mentioned it: people don't strictly need to remember to include mixins as you can override the blueprint that is used when someone does ember generate: http://www.ember-cli.com/#generators-and-blueprints