getting parameter value from nested routes - ember.js

I have my router set like :
this.resource('analytics', {path: '/analytics'}, function(){
this.resource('analyticsRuns', {path: ':exerciseRunId/analyticsRuns'},function(){
this.resource('analyticsRun',{path: ':runId'});
});
});
I jump to 'analyticsRuns' route using :
this.transitionToRoute('analyticsRuns',{"exerciseRunId":this.get('selectedExerciseRun.id')});
And my AnalyticsRunsIndexRoute is defined as :
AS.AnalyticsRunsIndexRoute = Ember.Route.extend({
model : function(params) {
var store = this.get('store');
//console.log(params); //returns empty object
//var exerciseRunId = AS.Analytics.get('exerciseRunId');
exerciseRunId = 577;
if(!(exerciseRunId)){
this.transitionTo('analytics');
}
store.find('analyticsRun',{'exerciseRunId':exerciseRunId});
return store.filter('analyticsRun', function(analyticRun){
return analyticRun.get('exerciseRunId') == exerciseRunId;
});
},
setupController : function(controller,model){
this._super(controller,model);
this.controllerFor('analysisTemplates').set('model',controller.get('store').find('analysisTemplate'));
}
});
I was wondering if I could access ":exerciseRunId" value in the AnalyticsRunsIndexRoute. Currently there isnothing set when I check the params arguments passed to this routes' model. On refresh however, the parameter becomes available to the AnalyticsRunRoute but only on refresh. So do I have to play with stateManagement to get the parameter value? or is there simpler way to access it. Thanks.
SOLUTION :
Again lots of thanks to Jeremy for walking through this. Here is how I have set up things now :
I defied routes like :
AS.AnalyticsRunsRoute = Ember.Route.extend({
model : function(params) {
return params;
}
});
AS.AnalyticsRunsIndexRoute = Ember.Route.extend({
model : function(params) {
var parentModel = this.modelFor('analyticsRuns');
var exerciseRunId = AS.Analytics.get('exerciseRunId')||parentModel.exerciseRunId;
var store = this.get('store');
if(!(exerciseRunId)){
this.transitionTo('analytics');
}
store.find('analyticsRun',{'exerciseRunId':exerciseRunId});
return store.filter('analyticsRun', function(analyticRun){
return analyticRun.get('exerciseRunId') == exerciseRunId;
});
},
setupController : function(controller,model){
this._super(controller,model);
this.controllerFor('analysisTemplates').set('model',controller.get('store').find('analysisTemplate'));
}
});

When calling transitionToRoute you should be passing a live object.
this.transitionToRoute('analyticsRuns',this.get('selectedExerciseRun'));
When you transition from route to route the model hook is skipped so it's important that you pass live objects either in transitionToRoute or in a link-to.
[UPDATE] in response to a comment:
If selectedExcerciseRun is not a live object, then you'd need to instantiate a live object before transitioning. Something like this :
var runId = this.get('selectedExerciseRun.id');
var promise = store.find('analyticsRun',{'exerciseRunId':runId});
promise.then(function(analyticsRun){
this.transitionToRoute('analyticsRun',analyticsRun);
});

Related

Ember promise not resolved when I expect it to be

I have a custom component that expects data and not a promise, but I am unsure if they way that I am obtaining the data is the right way.
Is this the right way to do it?
component hbs
{{x-dropdown content=salutations valuePath="id" labelPath="description" action="selectSalutation"}}
Doesn't work
controller (this is the way I expect things to work
import Ember from 'ember';
export default Ember.Controller.extend({
bindSalutations: function() {
var self = this;
this.store.find('salutation').then(function(data) {
self.set('salutations', data);
});
}.on('init'),
components/x-dropdown.js
import Ember from 'ember';
export default Ember.Component.extend({
list: function() {
var content = this.get('content');
var valuePath = this.get('valuePath');
var labelPath = this.get('labelPath');
return content.map(function(item) {
return {
key: item[labelPath],
value: item[valuePath],
};
});
}.property('content'),
This works
controller
bindSalutations: function() {
var self = this;
this.store.find('salutation').then(function(data) {
self.set('salutations', data.get('content')); // pass the content instead of just the data
});
}.on('init'),
component
...
list: function() {
var content = this.get('content');
var valuePath = this.get('valuePath');
var labelPath = this.get('labelPath');
return content.map(function(item) {
return {
key: item._data[labelPath], // access through the _data attribute
value: item._data[valuePath],
};
});
}.property('content'),
Ember Data returns a Proxy Promise. This means you can use the promise as if it were a collection or model itself, as long as you aren't dependent on the property being completely populated when you use it. If you really want the promise resolved, you should probably be setting it up in the route.
If you want it on your controller, you can be lazy and do it like so:
Controller
salutations: function() {
this.store.find('salutation');
}.property(),
Component
...
list: function() {
var content = this.get('content'),
valuePath = this.get('valuePath'),
labelPath = this.get('labelPath');
return content.map(function(item) {
return {
key: item.get(labelPath),
value: item.get(valuePath),
};
});
}.property('content.[]'),
Template
{{x-dropdown content=salutations valuePath="id" labelPath="description" action="selectSalutation"}}
The real trick is to watch if the collection is changing. Hence you'll see I changed the property argument to content.[]

How to avoid too many empty records?

Ember : 1.5.0-beta.2
Ember Data : 1.0.0-beta.7
I have the following router:
App.Router.map(function() {
this.resource('posts', function() {
this.route('new');
});
});
My PostsNewRoute creates a new record in the model hook:
App.PostsNewRoute = Ember.Route.extend({
model: function() {
return this.store.createRecord('post');
}
});
Since I don't want transient record to be visible, I filter them out in my PostsRoute:
App.PostsRoute = Ember.Route.extend({
model: function() {
this.store.find('post');
return this.store.filter('post', function(post) {
return !post.get('isNew');
});
}
});
This works as expected, but every transition to posts.new add a new record to the store, which is something I would like to avoid. So, instead of calling createRecord every time the model hook is called, I filter the store for an empty record and return this if there is one found:
App.PostsNewRoute = Ember.Route.extend({
model: function() {
var route = this;
return this.store.filter('post', function(post) {
return post.get('isNew');
}).then(function(result) {
return result.get('firstObject') || route.store.createRecord('post');
);
});
This gives me at the most one empty record.
My question: is there a better way to avoid my store being populated with (many) empty records ?
UPDATE:
Instead of filtering on the isNew attribute, I can probably use currentModel:
model: function() {
this.get('currentModel') || this.store.createRecord('post');
};
You can use this addon https://github.com/dockyard/ember-data-route to clean up when you leave a /new route. It hooks into the willTransition action hook that gets called on the route whenever a transition occurs.
The source code is a short read: https://github.com/dockyard/ember-data-route/blob/master/addon/mixins/data-route.js.
The alternative would be to not create a new record in the model hook, but according to a comment of yours it doesn't seem to be an option.

Custom Dynamic Segment (NOT ID) - EmberJS

I want to have a dynamic segment path in Ember without using the :id attribute
As per the Ember Guides, I'm using the serialize method to achieve this.
Heres my Router:
App.Router.map(function() {
this.resource("orders", function(){
this.resource('order', { path: ':order_sequence'}, function(){
this.route('edit');
})
});
});
And my Route:
var OrderRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('order', params.order_sequence)
},
serialize: function(model) {
return { order_sequence: model.get('sequence') };
}
});
module.exports = OrderRoute;
However, my URL's still behave using the id attribute in the path instead of the sequence attribute..
Any ideas?
Is your browser caching something, because that's correct. Are you passing in the id instead of the sequence/model in any of your transitionTo/transitionToRoute/link-to?
Oh, you aren't talking about the slug in the url, nor the route, you are talking about the id of your model. You need to create a serializer for that particular model and override the primary key
App.OrderSerializer = DS.RESTSerializer.extend({
primaryKey: 'sequence'
});
The Fixture Adapter has a constraint on defining the id, but you can lazily get around it by extending the fixture adapter and overriding a single method
App.OrderAdapter = DS.FixtureAdapter.extend({
fixturesForType: function(type) {
if (type.FIXTURES) {
var fixtures = Ember.A(type.FIXTURES);
return fixtures.map(function(fixture){
// aka we massasge the data a bit here so the fixture adapter won't whine so much
fixture.id = fixture.sequence;
var fixtureIdType = typeof fixture.id;
if(fixtureIdType !== "number" && fixtureIdType !== "string"){
throw new Error(fmt('the id property must be defined as a number or string for fixture %#', [fixture]));
}
fixture.id = fixture.id + '';
return fixture;
});
}
return null;
},
});

Example of how to use Zendesk's ember-resource adapter

Is there any working and current example on how to use Zendesk's ember-resource adapter with ember.js? I think I understand how to define the models, but I can't find any hint on how to use it in controllers and routes.
In general, there are two approaches for a given route: (1) go immediately to the page and fill in data as it becomes available (2) wait for the data to be fetched before transitioning.
Case 1 is quite straightforward. You create an instance of the model class, call fetch, and return it.
var FooRoute = Em.Route.extend({
model: function(params) {
var foo = Foo.create({ id: params.id });
foo.fetch();
return foo;
},
setup: function(foo) {
// foo is a Foo, but may not have its data populated
}
});
Case 2 is more complicated because Ember-Resource's fetch method returns a promise that resolves with two arguments -- the underlying JSON data and the model itself. An Ember.Route that returns such a promise will only pass the first to setup, so we have to create our own promise:
var FooRoute = Em.Route.extend({
model: function(params) {
var foo = Foo.create({ id: params.id }),
deferred = $.Deferred();
foo.fetch().then(
function(json, model) { deferred.resolve(model); },
function(error) { deferred.reject(error); }
);
return deferred.promise();
},
setup: function(foo) {
// foo is a Foo with its data populated
}
});

Can a nested ember.js route use a different model and still retain controller context?

I have a basic person object
PersonApp.Person = DS.Model.extend({
username: DS.attr('string')
});
I have a route to find all people
PersonApp.Router.map(function(match) {
this.resource("person", { path: "/" }, function() {
this.route("page", { path: "/page/:page_id" });
this.route("search", { path: "/search/:page_term" });
});
});
In my route I'm looking at the params coming in
PersonApp.PersonRoute = Ember.Route.extend({
selectedPage: 1,
filterBy: '',
model: function(params) {
if (get(params, 'page_id') !== undefined) {
this.selectedPage = get(params, 'page_id');
} else {
this.selectedPage = 1;
}
if (get(params, 'page_term') !== undefined) {
this.filterBy = get(params, 'page_term');
} else {
this.filterBy = '';
}
console.log(this.selectedPage);
console.log(this.filterBy);
return PersonApp.Person.find();
}
});
My nested routes are using a different model (not person directly) as they contain data that isn't persisted (and really only let me flip a bit on the controller)
Yet when I manually put something on the url or click a link that does a full blown transition the "params" coming into my model hook above are always empty.
Here is the basic page model I'm using (w/ search support)
PersonApp.Page = Ember.Object.extend({
term: ''
});
When a user does a search I have a view that invokes transitionTo
PersonApp.SearchField = Ember.TextField.extend({
keyUp: function(e) {
var model = PersonApp.Page.create({term: this.get('value')});
this.get('controller.target').transitionTo('person.search', model);
}
});
Any way I can pass this "page" model to a nested view and still retain the basic "person" controller context (ie- so I can manipulate the view around this array of model objects)