Suppose I have a variable title that runs an observer like below.
Ember.Route.reopenClass({
title: 'Ember Application',
_titleDidChange: function(){
console.log('Title Updated');
}.observes('title')
});
So whenever now a route is created and a new title is set i am expecting its observer to run. But its not happening.
App.IndexRoute = Ember.Route.extend({
title: 'index Route',
model: function() {
return ['red', 'yellow', 'blue'];
}
});
What should be done to make this functionality work like i wanted?
Here is the jsbin link
http://emberjs.jsbin.com/neges/1/edit
UPDATE: ok..i found something from EmberJS github. They are already trying to implement title same way but need to do changes in ember.js which is not an option for me. Any Simple way to do same https://github.com/emberjs/ember.js/pull/3689/files#r9367594
How about this:
App = Ember.Application.create();
Ember.Route.reopen({
title: 'Ember Application',
_titleDidChange: function(){
console.log('Title Updated: ' + this.get("title"));
}.observes('title').on("init")
});
App.IndexRoute = Ember.Route.extend({
title: 'index Route'
});
Two crucial changes were needed to make your code to work:
Switched from reopenClass to reopen. reopenClass is used to add static properties to the class itself, not its instances.
Added on("init"), which will ensure property change events will trigger during object initialization, which is what you need.
Updated jsbin is here.
Related
I am trying to implement a controller needing another (CampaignsNew needing AppsIndex), which looks like
App.CampaignsNewController = Ember.Controller.extend({
needs: ['appsIndex']
});
And in my CampaignsNew template I am showing it via
{{#if controllers.appsIndex.content.isUpdating}}
{{view App.SpinnerView}}
{{else}}
{{#each controllers.appsIndex.content}}
{{name}}
{{/each}}
{{/if}}
However controllers.appsIndex.content.isUpdating is never true. I.e. it attempts to show the data before it has been loaded.
My AppsIndex route has the model overridden:
App.AppsIndexRoute = Ember.Route.extend({
model: function(controller) {
var store = this.get('store').findAll('app');
}
...
});
I can get it to work if I put the same code within my CampaignsNew route and modify the template to each through controller.content. Which says to me that needs is not using the route? It also works if I go to the /apps page and it loads the data, and then navigate to the /campaigns/new page.
How do I get this to work? Thanks!
Edit:
As requested, the relevant parts of my router:
App.Router.map(function() {
this.resource('apps', function() {
...
});
this.resource('campaigns', function() {
this.route('new');
});
});
And the AppsIndex is accessed at /apps and CampaignsNew is at /campaigns/new
Edit2:
After implementing the suggestion by #kingpin2k, I've found that Ember is throwing an error. Below are the updated files and the error received.
App.CampaignsNewController = Ember.ObjectController.extend({
pageTitle: 'New Campaign'
});
App.CampaignsNewRoute = Ember.Route.extend({
model: function(controller) {
return Ember.RSVP.hash({
campaign: this.store.createRecord('campaign'),
apps: this.store.find('app')
});
// return this.store.createRecord('campaign');
},
setupController: function(controller, model){
controller.set('apps', model.apps);
this._super(controller, model.campaign);
}
});
Ember throws this error:
Error while loading route: Error: Assertion Failed: Cannot delegate set('apps', <DS.RecordArray:ember689>) to the 'content' property of object proxy <App.CampaignsNewController:ember756>: its 'content' is undefined.
I read online that this is because the content object doesn't exist. If I set it like so:
App.CampaignsNewController = Ember.ObjectController.extend({
content: Ember.Object.create(),
...
});
Then the page loads without error, and when inspecting the Ember Chrome extension, I can see the data has loaded. But it doesn't show on the page. Which I suppose happened because the content object existed and so Ember didn't wait for the model's promise to fulfill before rendering the template. Seems odd that you should have to define content in such a way though. Any insight on how to handle this?
Edit3: Question answered for me in another thread
Based on your router, apps isn't a parent of campaigns/new.
This means someone could hit #/campaigns/new and Ember would hit ApplicationRoute, CampaignsRoute, and CampaignsNewRoute to populate the necessary information for the url requested. Using needs as a way of communicating between controllers really only makes sense in an ancestral pattern (aka communicating with your parents, grandparents etc).
Just as another quick note, AppsIndex is a route of Apps, it won't be hit when your url includes a child. e.g.
Router
this.resource('apps', function() {
this.resource('chocolate', function(){
.....
});
});
Url being hit
#/apps/chocolate
Routes that will be hit
ApplicationRoute
AppsRoute
ChocolateRoute
ChocolateIndexRoute
The index route is only hit when you don't specify a route of a resource, and you are hitting that exact resource (aka nothing past that resource).
Update
You can return multiple models from a particular hook:
App.FooRoute = Em.Route.extend({
model: function(){
return Em.RSVP.hash({
cows: this.store.find('cows'),
dogs: this.store.find('dogs')
});
}
});
If you want the main model to still be cows, you could switch this up at the setupController level.
App.FooRoute = Em.Route.extend({
model: function(){
return Em.RSVP.hash({
cows: this.store.find('cows'),
dogs: this.store.find('dogs')
});
},
setupController: function(controller, model){
controller.set('dogs', model.dogs); // there is a property on the controller called dogs with the dogs
this._super(controller, model.cows); // the model backing the controller is cows
}
});
Check out the second answer here, EmberJS: How to load multiple models on the same route? (the first is correct as well, just doesn't mention the gotchas of returning multiple models from the model hook).
You can also just set the property during the setupController, though this means it won't be available when the page has loaded, but asynchronously later.
Which controller?
Use Controller if you aren't going to back your controller with a model.
App.FooRoute = Em.Route.extend({
model: function(){
return undefined;
}
});
Use ObjectController, if you are going to set the model of the controller as something, that isn't a collection.
App.FooRoute = Em.Route.extend({
model: function(){
return Em.RSVP.hash({
cows: this.store.find('cows'),
dogs: this.store.find('dogs')
});
}
});
Use ArrayController if that something is going to be a collection of some sort.
App.FooRoute = Em.Route.extend({
model: function(){
return ['asdf','fdsasfd'];
}
});
Note
If you override the setupController, it won't set the model of the controller unless you explicitly tell it to, or use this._super.
App.FooRoute = Em.Route.extend({
model: function(){
return Em.RSVP.hash({
cows: this.store.find('cows'),
dogs: this.store.find('dogs')
});
},
setupController: function(controller, model){
controller.set('cows', model.cows);
controller.set('dogs', model.dogs);
// uh oh, model isn't set on the controller, it should just be Controller
// or you should define one of them as the model
// controller.set('model', model.cows); or
// this._super(controller, model.cows); this does the default setupController method
// in this particular case, ArrayController
}
});
You guys may need more details to answer this, but I figured it might be simple. I'm using Ember Data and the fixture adapter.
This correctly maps the URL to each item in my model.
App.Router.map(function() {
this.resource('quotes', function(){
this.resource('quote', {path: '/:quote_id' })
});
});
App.QuotesRoute = Ember.Route.extend ({
model: function(){
return App.Quote.find();
}
});
But this does not.
App.Router.map(function() {
this.resource('quotes', {path: '/:quote_id' });
});
App.QuotesRoute = Ember.Route.extend ({
model: function(){
return App.Quote.find();
}
});
Does Ember only know to return App.Quote.find(quote_id) if it's a nested resource?
The controller for your route in the second example will be generated as an Ember.ArrayController, which will mismatch with the controller generated for your '/:quote_id' path, as it's a singleton.
What happens if you pass a single model, by using return App.Quote.find(1); or something that will return one record.
I am still trying to understand what exactly you want to happen with that second code example. what kind of logic are you expecting?
I have two controllers which both load to the same outlet, so only one can be active at one time. Both observe a property on a third controller like this:
App.SearchController = Ember.ObjectController.extend({
needs: ['navigation'],
updateResults: function () {
console.log('load search data');
}.observes('controllers.navigation.search')
});
Full sample
http://jsfiddle.net/FMk7R/1/
When the property changes some data is fetched. If I click on both links so that both are loaded, then when the property changes, both controllers receive the observes event and load the data. I'd like to load the data only in the one which is visible.
How can I figure out which controller is currently active and load the data only in the active one?
Ideally your controllers should not know that they are active. One alternative is to invert the relationship, so that NavController is responsible for changing a query property of the "active" controller.
** UPDATE - Adding example based on comment **
App.SearchRoute = Ember.Route.extend({
setupController: function(controller) {
this.controllerFor('navigation').set('active', controller);
}
});
App.ImagesRoute = Ember.Route.extend({
setupController: function(controller) {
this.controllerFor('navigation').set('active', controller);
}
});
App.SearchController = Ember.ObjectController.extend({
loadResults: function (query) {
console.log('loading web search data for: ', query);
}
});
App.ImagesController = Ember.ObjectController.extend({
loadResults: function (query) {
console.log('loading image search data for: ', query);
}
});
App.NavigationController = Ember.ObjectController.extend({
search: '',
active: null,
searchDidChange: function() {
this.get('active').loadResults(this.get('search'));
}.observes('search', 'active')
});
See http://jsfiddle.net/F3uFp/1/
Another alternative is to use computed properties instead. Ember will only refresh computed properties that are actually required to render the active view. For example:
App.SearchController = Ember.ObjectController.extend({
needs: ['navigation'],
results: function () {
console.log('loading web search data');
return("web search results");
}.property('controllers.navigation.search')
});
See updated fiddle here: http://jsfiddle.net/ZTnmp/
http://jsfiddle.net/FMk7R/1/
hi i have the following route:
MB3.PlaylistRoute = Ember.Route.extend({
model: function(params) {
return MB3.Playlist.find(params.playlist_id);
}
});
The playlist has a hasMany realtion with tracks. in the playlist view i want do do some logic with an attribute of the first track of the playlist.
so i added this code:
MB3.PlaylistView = Ember.View.extend({
didInsertElement: function() {
console.log(this.get("controller.tracks").objectAt(0).get("title"));
}
});
The problem is title is undefined (i think because it is not yet loaded. the second thing i tried is waiting for the didLoad event:
MB3.PlaylistView = Ember.View.extend({
didInsertElement: function() {
var self=this;
this.get("controller.tracks").on("didLoad", function() {
console.log(self.get("controller.tracks").objectAt(0).get("title"));
});
}
});
but this logges null as well. How do i accomplish that?
Like Adrien said in the comments, it seems you are running into issue 587. That said, I don't think you actually need the "didLoad" callback in this case. Instead, try using a computed property to get the video_id or track title. For example:
MB3.PlaylistView = Ember.View.extend({
firstTrackTitle: function() {
return this.get('controller.tracks.firstObject.title');
}.property('controller.tracks.firstObject.title')
});
Then in your template, embed the player if this property is defined:
{{#if view.firstTrackTitle}}
embed code here
{{/if}}
FWIW I would put this logic in controller instead of view, but same idea.
I'm trying to access an instance of a controller that has been wired automatically using App.initialize();
I've tried the below but it returns a Class not an instance.
Ember.get('App.router.invitesController')
I have a quick post about this exact subject on my Blog. It's a little big of a different method, but seems to work well for Ember.js RC1.
Check it out at: http://emersonlackey.com/article/emberjs-instance-of-controller-and-views
The basic idea is to do something like:
var myController = window.App.__container__.lookup('controller:Posts');
This answer works with RC1/RC2.
Now you can use the needs declaration in order to make the desired controller accessible. Here's an example:
Suppose I want to get something from my SettingsController from within my ApplicationController. I can do the following:
App.SettingsController = Ember.Controller.extend({
isPublic: true
});
App.ApplicationController = Ember.Controller.extend({
needs: 'settings',
isPublicBinding: 'controllers.settings.isPublic'
});
Now in the context of my ApplicationController, I can just do this.get('isPublic')
You can access a controller instance inside an action in the router via router.get('invitesController'), see http://jsfiddle.net/pangratz666/Pk4k2/:
App.InvitesController = Ember.ArrayController.extend();
App.Router = Ember.Router.extend({
root: Ember.Route.extend({
route: '/',
index: Ember.Route.extend({
route: '/',
connectOutlets: function(router, context) {
var invitesController = router.get('invitesController');
},
anAction: function(router) {
var invitesController = router.get('invitesController');
}
})
})
});
You can access any controller instance by name using lookup method of Application instance.
To get Application instance you can use getOwner from any route or controller.
const controllerName = 'invites';
Ember.getOwner(this).lookup(`controller:${controllerName}`));
Works for me in Ember 2.4 - 3.4.