Model unavailable in sub-route - ember.js

App.Router.map(function() {
this.resource('products', function() {
this.resource('product', { path: ':product_id' }, function() {
this.route('general');
});
})
});
App.ProductsRoute = Ember.Route.extend({
model: function() {
return this.store.find('product');
}
});
App.ProductRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('product', params.product_id);
}
});
Templates:
<script type="text/x-handlebars" data-template-name="product">
Showing {{ name }}
<p>{{ outlet }}</p>
</script>
<script type="text/x-handlebars" data-template-name="product/general">
General template for {{ name }}
</script>
In the /products/3 view the name shows up as it should, but not in the /products/3/general view. Anybody know why?
I have tried to copy the App.ProductRoute and rename it to App.ProductGeneralRoute to find the correct model, but then the params does not exist.

In Ember, nested routes don't have access to their parent routes model. There are two ways to access parent models in a child route.
App.ProductGeneralRoute = Ember.Route.extend({
model: function() {
return this.modelFor('product');
}
});
This sets the model on the ProductGeneral route by getting the model for the ProductRoute. Or you can use needs:
App.ProductGeneralController = Ember.ObjectController.extend({
needs: ['product']
});
In the latter example, you will have access to controllers.product, which will allow you to call controllers.product.model in the template.
See this article for more info on needs.

Related

Computed property on a model in a different controller

I'm building the mandatory TODO app to learn ember.
I have tasks and tags in a belongsTo/hasMany relationship (each tag hasMany tasks). When showing tasks, I want to show a computed property on each available tag.
Models:
App.Tag = DS.Model.extend({
tasks: DS.hasMany('task', {async: true}),
..
});
App.Task = DS.Model.extend({
tag: DS.belongsTo('tag', {async: true}),
..
});
Route:
App.TasksRoute = Ember.Route.extend({
model: function(params) {
return Ember.RSVP.hash({
tasks: this.store.find('task'),
tags: this.store.find('tag')
});
},
setupController: function(controller, model) {
this.controllerFor('tasks').set('content', model.tasks);
this.controllerFor('tags').set('content', model.tags);
}
});
Tags controller:
App.TagsController = Ember.ArrayController.extend({
needs: ["tag"]
})
Tag controller:
App.TagController = Ember.ObjectController.extend({
taskCount: function() {
// FOLLOWING DOES NOT WORK
return this.get('tasks.length')
}.property('tasks')
});
Tag partial:
<ul>
{{#each tag in model}}
<li>
{{tag.name}} ({{controllers.tag.taskCount}} tasks)
</li>
{{/each}}
</ul>
The computed property 'taskCount' does not work. There is something wrong with 'this'.
Is this canonical way of doing it? And if so, what is wrong? Thanks
EDIT: FIXED
I had missed out
App.ApplicationSerializer = DS.ActiveModelSerializer.extend();
And I've used render to get the controller decoration:
{{render 'tag' tag}}
which calls the controller before rendering

Ember.js Masonry rendering doesn't wait for Data Models to be generated

I am trying to build a masonry view of the top selling Items in a hypothetical eCommerce Site but Masonry is being rendered before the Data Models can be generated over RESTAdapter. Here are is my Ember.js code:
App.Userprofile = DS.Model.extend({
loggedIn: DS.attr('boolean'),
name: DS.attr('string'),
totalItems: DS.attr('number'),
});
App.ApplicationRoute = Ember.Route.extend({
setupController: function(controller) {
this.store.find('userprofile', 'bat#man.com').then (function(userprofile) {
controller.set ('model', userprofile);
});
}
});
App.ApplicationAdapter = DS.DjangoRESTAdapter.extend({
host: HOST,
namespace: 'api'
});
App.ApplicationView = Ember.View.extend({
elementId: '',
classNames: ['container','fullwidth'],
templateName: 'application'
});
App.Cloud = DS.Model.extend({
item: DS.attr('string'),
numberItems: DS.attr('number'),
rank: DS.attr('number')
});
App.CloudAdapter = DS.DjangoRESTAdapter.extend({
host: HOST,
namespace: 'api',
});
App.CloudController = Ember.ObjectController.extend({
needs: ['application'],
cloudSize: function() { // Determines the size of the div
var cloudsize = Math.round (this.get('model.numberItems') * 5 / this.get('controllers.application.totalItems')) + 1;
var divName = "score" + cloudsize.toString();
return divName;
}.property('model.numberItems', 'controllers.application.totalitems')
});
App.ItemcloudRoute = Ember.Route.extend({
setupController: function(controller) {
this.store.findAll('cloud').then (function(itemcloud) {
controller.set ('model', itemcloud);
});
}
});
App.ItemcloudController = Ember.ArrayController.extend({
needs: ['cloud', 'application'],
sortProperties: ['rank'],
});
App.ItemcloudView = Ember.View.extend({
elementId: 'magicgrid',
classNames: ['cloudcontainer'],
templateName: 'itemcloud',
didInsertElement: (function() {
this._super();
Ember.run.scheduleOnce('afterRender', this, this.applyMasonry);
}).observes('controller.itemcloud'),
applyMasonry: function() {
setTimeout( function() { // settimeout to ensure masonry is called after data models are generate
console.log ("applyMasonry being called");
$('#magicgrid').masonry({
itemSelector: '.company',
isAnimated: true
});
}, 2000);
}
});
Here is the portion of the template file where itemcloud is generated.
<script type="text/x-handlebars" data-template-name='itemcloud'>
{{#each controller.model itemController="cloud"}}
<div {{bind-attr class=":company cloudSize"}}>
<div class="companylogo">
<img src="images/logos/color-logos/logo-01.jpg" />
</div>
<div class="count">{{numberItems}}</div>
</div>
{{/each}}
<div class="clearfix"></div>
</script>
Now, I am struggling to find a way to hold the Masonry rendering until after the data is fetched due to the asynchronous nature of the data fetching and the template rendering. My research says that using a View for the CloudController Objects would be useful, but am trying to figure out if there is something I am missing in my current design. Also, if someone can provide pointers to use Views correctly here for the CloudController Objects
Let me know if I need to provide any more clarifications. Thanks!
if you doing it in the setupController Ember assumes the model is already ready and continues rendering the page despite the response not coming back from the server.
The easiest way to do it is to return your model/promise in the model hook. Ember will wait on rendering the page until the model has been resolved.
App.ItemcloudRoute = Ember.Route.extend({
model: function(){
this.store.find('cloud');
}
});
The code above will do the same thing your code was doing, except Ember will wait for the find to resolve before creating and setting the model on the controller.
As per kingpin2k comments updating the answer to reflect the working code:
App.ApplicationRoute = Ember.Route.extend({
model: function() {
return this.store.find ('userprofile', 'bat#man.com');
},
setupController: function(controller, model) {
controller.set ('model', model);
}
});

Ember.js setup controller and then accesing model within the controller

I'm new to Ember.js, this is my first app which has a notifications area, always visible. As this notification area is included in the application template and there is no specific route for it, I added the number using the {{render}} Helper and setting the model from the ApplicationRoute:
<script type="text/x-handlebars">
...
{{#link-to "notifications"}}
{{ render "notification-totals" }}
{{/link-to}}
<div class="dropdown">
{{outlet notifications}}
</div>
...
</script>
<script type="text/x-handlebars" data-template-name="notification-totals">
{{this.firstObject.total}}
</script>
The ApplicationRoute sets the model to the controller:
App.ApplicationRoute = Ember.Route.extend({
setupController: function() {
this.controllerFor('notification-totals').set('model',this.store.find('notification.total'));
}
});
The Model:
App.NotificationTotal = DS.Model.extend({
total: DS.attr('number')
});
How can I access the model within the Controller? Nothing I try seems to work, for example:
App.NotificationTotalsController = Ember.ObjectController.extend({
total: function() {
var model = this.get('model');
.....
}.property()
});
Your code should work fine. You should be getting an array of your model objects, because that's what the route is setting as model.
For example:
<script type="text/x-handlebars">
<div><h3>Notifications:</h3>
{{ render "notification-totals" }}</div>
</script>
<script type="text/x-handlebars" data-template-name="notification-totals">
{{total}}
</script>
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
App.ApplicationRoute = Ember.Route.extend({
setupController: function() {
var data = [
{
total: 7
}, {
total: 8
}, {
total: 12
}
];
this.controllerFor('notification-totals').set('model', data);
}
});
App.NotificationTotalsController = Ember.ObjectController.extend({
total: function() {
var model = this.get('model');
return model
.mapBy("total")
.reduce(function (prev, cur) {
return prev + cur;
}, 0);
console.log(model);
}.property("model.#each.total")
});
This controller will access all the model objects and generate the sum ({{this.firstObject.total}} will get you totals only from the first object). Working demo here.
If you're still getting nothing, check if your data source is getting anything (this demo uses hardcoded values instead of ember data).

Attempting to create a profile page but App.User.find() errors

I have a simple app on fiddle http://jsfiddle.net/kitsunde/qzj2n/2/
<script type="text/x-handlebars">
{{outlet}}
</script>
<script type="text/x-handlebars" id="profile">
Profile Page
{{ email }}
</script>
Where I'm trying to display a profile page.
window.App = Ember.Application.create();
App.Router.map(function () {
this.resource('profile', {path: '/'});
});
App.User = DS.Model.extend({
email: DS.attr('string')
});
App.User.FIXTURES = [
{
id: 1,
email: 'herpyderp#gmail.com'
}
];
App.ProfileRoute = Ember.Route.extend({
model: function(){
return App.User.find().get('firstObject');
}
});
But I'm getting an exception:
Error while loading route: TypeError: undefined is not a function
What am I missing?
There are a few things missing. You can find the fixed fiddle here:
http://jsfiddle.net/47cHy/
window.App = Ember.Application.create();
App.ApplicationAdapter = DS.FixtureAdapter;
App.Router.map(function () {
this.resource('profile', { path: '/' });
});
App.User = DS.Model.extend({
email: DS.attr('string')
});
App.User.FIXTURES = [
{
id: 1,
email: 'herpyderp#gmail.com'
}
];
App.ProfileRoute = Ember.Route.extend({
model: function() {
return this.store.find('user').then(function(users) {
return users.get('firstObject');
});
}
});
Your template had the id index and not the name of the route profile
You have to tell Ember specifically to use the fixture adapter.
You accessed the model directly via the global object. You should let Ember do the work via the internal resolver and use this.store.find.
.find() returns a promise. You should get the first object in the then handler and return it there.

How can I get ember to persist my edited model changes to save across routes?

I have a fiddle (http://jsfiddle.net/kitsunde/3FKg4/) with a simple edit-save application:
<script type="text/x-handlebars">
{{outlet}}
</script>
<script type="text/x-handlebars" id="profile/edit">
Edit.
<form {{action 'save' on="submit"}}>
<div>
<input type="email" {{bind-attr value="email"}}>
</div>
<button>Save</button>
</form>
</script>
<script type="text/x-handlebars" id="profile/index">
{{#link-to 'profile.edit'}}Edit{{/link-to}}
{{email}}
</script>
And my application:
window.App = Ember.Application.create();
App.ApplicationAdapter = DS.FixtureAdapter.extend();
App.Router.map(function () {
this.resource('profile', {path: '/'}, function(){
this.route('edit');
});
});
App.ProfileRoute = Ember.Route.extend({
model: function() {
return this.store.find('user').then(function(users){
return users.get('firstObject');
});
}
});
App.ProfileEditRoute = App.ProfileRoute;
App.ProfileEditController = Ember.ObjectController.extend({
actions: {
save: function(){
var profile = this.get('model');
profile.setProperties({email: this.get('email')});
profile.save();
this.transitionTo('profile');
}
}
});
App.User = DS.Model.extend({
email: DS.attr('string')
});
App.User.FIXTURES = [
{
id: 1,
email: 'herpyderp#gmail.com'
}
];
When I hit save and it goes back to profile/index it doesn't have an updated model and when I go back to profile/edit the edit isn't there. I realize I could use {{input value=email}} which does seem to remember the model changes, but that seems to persist the changes to the model as I type which isn't what I want.
What am I missing?
The save method returns a promise, you could transition when the promise is resolved as:
var route = this;
profile.save().then(function() {
route.transitionTo('profile');
}, function() {
// TODO: implement error logic
});
In that case, your method will be updated when the application goes back to the index state.
I fixed it with 2 changes. First since I was grabbing this.get('email') I was getting the models email address and not the one from input field, so it was actually never updating the data.
<script type="text/x-handlebars">
{{outlet}}
</script>
<script type="text/x-handlebars" id="profile/edit">
Edit.
<form {{action 'save' on="submit"}}>
<div>
{{input value=email}}
</div>
<button>Save</button>
</form>
{{#link-to 'profile'}}Back{{/link-to}}
</script>
<script type="text/x-handlebars" id="profile/index">
{{#link-to 'profile.edit'}}Edit{{/link-to}}
{{email}}
</script>
Second to deal with only updating the model on save I used ember-data transaction handling to rollback the commit when navigating away from the current route, unless it had been saved. I also moved my logic into the router.
window.App = Ember.Application.create();
App.ApplicationAdapter = DS.FixtureAdapter.extend();
App.Router.map(function () {
this.resource('profile', {path: '/'}, function(){
this.route('edit');
});
});
App.ProfileRoute = Ember.Route.extend({
model: function() {
return this.store.find('user').then(function(users){
return users.get('firstObject');
});
}
});
App.ProfileEditRoute = App.ProfileRoute.extend({
deactivate: function(){
var model = this.modelFor('profile');
if(model.get('isDirty') && !model.get('isSaving')){
model.rollback();
}
},
actions: {
save: function(){
this.modelFor('profile').save();
this.transitionTo('profile');
}
}
});
App.User = DS.Model.extend({
email: DS.attr('string')
});
App.User.FIXTURES = [
{
id: 1,
email: 'herpyderp#gmail.com'
}
];
Updated fiddle: http://jsfiddle.net/kitsunde/3FKg4/2/