rendering one item from a list in Ember - ember.js

In my Ember app, I get a list of all the restaurants using an ajax call copied from Discourse co-founder's blog post http://eviltrout.com/2013/02/27/adding-to-discourse-part-1.html
App.Restaurant.reopenClass({
findAll: function() {
return $.getJSON("restaurants").then(
function(response) {
var links = Em.A();
response.restaurants.map(function (attrs) {
links.pushObject(App.Restaurant.create(attrs));
});
return links;
}
);
},
I have a Restaurants route set up which calls the findAll shown above and renders it into the application template
App.RestaurantsRoute = Ember.Route.extend({
model: function(params) {
return(App.Restaurant.findAll(params));
},
renderTemplate: function() {
this.render('restaurants', {into: 'application'});
}
});
The restaurants are displayed as a restaurants template like this with a link to each individual restaurant. I've also included the restaurant template
<script type="text/x-handlebars" id="restaurants">
<div class='span4'>
{{#each item in model}}
<li> {{#link-to 'restaurant' item}}
{{ item.name }}
{{/link-to }}</li>
{{/each}}
</ul>
</div>
<div class="span4 offset4">
{{ outlet}}
</div>
</script>
In the Ember router, I have a parent/child route set up like this
this.resource("restaurants", function(){
this.resource("restaurant", { path: ':restaurant_id'});
});
Therefore, I'm hoping that when I click on the link to a particular restaurant in the restaurants list, it'll insert this restaurant template into the outlet defined in the restaurantS (plural) template
<script type="text/x-handlebars" id="restaurant">
this text is getting rendered
{{ item }} //item nor item.name are getting rendered
</script>
This restaurant template is getting rendered, however, the data for the item is not getting displayed.
When I click {{#link-to 'restaurant' item}} in the list, item represents that restaurant.
In this setup, does Ember need to make another ajax call to retrieve that particular item, even though it's already been loaded from the findAll call?
In the event that I do need to query for the individual restaurant (again) I created a new route for the individual restaurant
App.RestaurantRoute = Ember.Route.extend({
model: function(params) {
console.log(params);
console.log('resto');
return App.Restaurant.findItem(params);
}
});
and a findItem on the Restaurant model
App.Restaurant.reopenClass({
findItem: function(){
console.log('is this getting called? No...');
return 'blah'
}
but none of those console.logs are getting called.
In the Ember starter video https://www.youtube.com/watch?v=1QHrlFlaXdI, when Tom Dale clicks on a blog post from the list, the post appears in the template defined for it without him having to do anything more than set up the routes (as I did) and the {{outlet}} within the posts template to receive the post.
Can you see why the same is not working for me in this situation?

When you navigate to the restaurant route, the item will be the model to this route.
So in your template, if you try
<script type="text/x-handlebars" id="restaurant">
this text is getting rendered
{{ model.name }}
</script>
You'll be able to see the name of the restaurant
And also the model hook is not called, and the further console.logs are not working,
because
Note: A route with a dynamic segment will only have its model hook called when it is entered via the URL. If the route is entered through a transition (e.g. when using the link-to Handlebars helper), then a model context is already provided and the hook is not executed. Routes without dynamic segments will always execute the model hook.
Hope everything will be clear now.

Related

Update ember component on model change

Using Ember 1.13
I have two nested resources, one of which renders a component based off the model returned by a dynamic route
something like
Router.map(function() {
this.resource('maps', function () {
this.resource('map', { path: '/:map_id' });
});
});
and a template for a map which renders a component
map.hbs
{{some-component model=model}}
{{#each maps as |map|}}
{{#link to 'map' map}}{{map.name}}{{/link-to}}
{{/each}}
when I first hit
/maps/1
the component renders
when I hit one of the links and go to
/maps/2
it appears as if the route never gets hit and the component never updates
is this a result of using link-to or is it true the route is not getting hit because just changing the model inside of a route does cause the same lifecyle hooks to go off?
What is the best way to force this component to rerender?
You're probably doing something wrong.
Here's a basic working example:
<h3>maps.index</h3>
<ul>
{{#each model as |item|}}
<li>
{{link-to item.name 'maps.map' item}}
</li>
{{/each}}
</ul>
<h3>maps.map</h3>
{{link-to "Back to index" 'maps.index'}}
<hr>
{{x-map map=model}}
<h4>components/x-map</h4>
<p>Id: {{map.id}}</p>
<p>name: {{map.name}}</p>
App.Router.map(function() {
this.route('maps', function () {
this.route('map', { path: '/:map_id' });
});
});
App.MapsIndexRoute = Ember.Route.extend({
model: function () {
return this.store.findAll('map');
}
});
App.MapsMapRoute = Ember.Route.extend({
model: function (params) {
return this.store.findRecord('map', params.mapId);
}
});
App.Map = DS.Model.extend({
name: DS.attr('string')
});
Demo: http://emberjs.jsbin.com/voquba/4/edit?html,js,output
Note that instead of passing the whole record into the child route:
{{link-to item.name 'maps.map' item}}
You can pass only its ID:
{{link-to item.name 'maps.map' item.id}}
This is useful when you know the ID but don't have the whole record at hand. Ember Data will look up the record of given ID in the store. If it's not there, it'll fetch it via the route's model hook.

Ember - #each pass the instance of the model

For a small webapp I'm trying to do the following:
I have a list of objects (achievement-model)that's being served through a json api
Router
export default Ember.Route.extend({
model:function(){
return this.store.find('achievement');
});
});
Model
export default DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
});
Template
{{#each a in model}}
<div>
<h4>{{a.name}}</h4>
<p>{{a.description}}</p>
<button {{action 'addThis'}}/>
</div>
{{/each}}
The setup of the app is that there is a list of achievements. I want one list of achievements in a database. Every user that logs in can add with the button his own achievements to his profile. If a user logs in he should see the list of all the achievements but the one he already added to his profile should have a green background color and the button removed. I know this can be done with if-statements etc.
The problem however is, how do i pass the specific model to the controller so i can log this to the userprofile? I tried the following:
<button {{action 'addThis' a}}/>
and then in the controller
actions:
addThis: function(obj){
console.log(obj);
});
which logs the object, but somehow I can't acces it to get let's say the name or id to copy it to the user-profile.
I also don't know if this is the best approach for what I'm trying to achieve?
Edit
I think this has something to do with promises. I can see the data is logged in the above console.log. I just don't know how to target it. it's wrapped in _data. I tried the afterModel to wait untill everything's loaded, but that doesn't seem to work.
What you could is to use an ItemController, e.g. which handles each item in the ArrayController,
e.g.
{{#each a in model itemController="achievement"}}
<div>
<h4>{{a.name}}</h4>
<p>{{a.description</p>
<button {{action 'addThis'}}/>
</div>
{{/each}}
Since the itemController is "achievement", by naming convention, the controller becomes
App.AchievementController = Ember.ObjectController.extend({
init: function() {
var name = this.get('name');
var description = this.get('description');
}
});

Emberjs: Accessing parent route model which is a Promise (master-detail)

I've got master-detail page layout as on image. I access this page through #/masters/:master_id app url.
Routes a defined as follows:
App.Router.map(function() {
this.resource('masters', { path: '/masters' }, function() {
this.route('detail', { path: '/:master_id' });
});
});
App.MastersRoute = Ember.Route.extend({
model: function() {
return App.DataStore.getData('/api/masters'); //returns Promise!
},
setupController: function(controller, model) {
controller.set("content", model);
}
});
App.MastersDetailRoute = Ember.Route.extend({
model: function(params) {
return this.modelFor("masters").find(function(item) {
return item.get("id") == params.master_id;
});
}
});
Templates:
<script type="text/x-handlebars-template" data-template-name="masters">
<div id="masters-grid">
{{#each master in model}}
<div {{action "show" master}}>
{{master.name}}
</div>
{{/each}}
</div>
<div id="detail">
{{outlet}}
</div>
</script>
<script type="text/x-handlebars-template" data-template-name="masters/detail">
{{model.name}} <br />
{{model.age}} <br />
{{model.address}} <br />
</script>
When clicking through masters in the grid I want to show their details in Detail outlet and I do not want to reload all masters from API when changing the master selection.
I have a problem with MastersDetailRoute's model, because this.modelFor("masters") returns undefined. I think, it is caused by returning Promise in model hook. Any idea or workaround how to access one item from Masters model or controller in "child route" model hook?
I see a few things here.
when defining routes that have the same url as the route name theres no need to specify the path
the detail route should also be a resource as it is a route backed by a model
In the Masters route returning a promise is correct and supported natively by ember. The route wont be resolved until the promise is.
setup controller isn't required
its usually best to do the required api call to fetch the individual record in the detail route. This will only be used when loading the page for the first time (if f5 ing or coming from a bookmark)
in your masters template you can use id instead of typing data-template-name or better still look into use ember-cli/brocolli or grunt to precompile your templates
to prevent ember refetching your model when selecting a row use the handlebars helper link-to
{{#link-to 'masterDetail' master}}
{{master.name}}
{{/link-to}}
just to clarify, using link-to in this way passes the object specified in the second parameter as the model to the specified route (first parameter). In your case master will now be set as the model to the master detail route.
in masters detail theres no need to type "model" the default context (i.e. the value of "this") in your template is the controller, then if the property is not found on the controller it looks for it in the model.
Hope this helps

Ember.js active link class with query params

In an indexview I have links that set the sorting:
# Template
{{#link-to 'products' (query-params sortBy="title")}}Title{{/link-to}}
{{#link-to 'products' (query-params sortBy="price")}}Price{{/link-to}}
# Controller
queryParams: ['sortBy']
sortBy: 'id'
sortProperties: ( ->
[#get("sortBy")]
).property("sortBy")
That generates links that always have the class of 'active', but I want to highlight the currently active sort filter. What is the best way to do it?
I tried binding to a computed property like this:
{{#link-to 'products' (query-params sortBy="price") classNameBindings='sortByPrice'}}Price{{/link-to}}
sortByPrice: -> (
#get('sortBy') == 'price'
).property('sortBy')
That didn't quite work, but even if it did, that's not DRY at all – and eventually I would like to add a lot of different attributes on which to sort.
As I understand, the problem is that ember adds the 'active' class when it's in the context of that controller, which it always is with different query-params.
(Running the latest canary build of Ember as of 14th June)
This has been fixed in Ember Canary, as of https://github.com/emberjs/ember.js/pull/5109
QueryParams should add the "active" class based on whether the declared parameter in the {{#link-to}} helper has the same value as the attribute at that moment, as I can demonstrate in this jsbin.
That said, I'm having the same problem, so I believe there's some fringe case where this doesn't work right, and I'd be happy if you could modify this example to reflect that.
I'm facing the same problem now and I have temporary solution.
<!-- Posts Template -->
<!-- Categories -->
<div class="block step visible-desktop visible-tablet">
<div class="header">
<h3>Category</h3>
</div>
<div class="area categories">
<ul>
{{#each staticCategory in controller.staticCategories}}
{{post-category currentCategory=currentCategory staticCategory=staticCategory}}
{{/each}}
</ul>
</div>
</div>
<!-- Categories end -->
//Posts Controller
staticCategories: ['Front-End', 'JavaScript', 'jQuery', 'null'],
currentCategory: function () {
return this.get('category');
}.property('category'),
queryParams: ['category'],
category: null,
filteredContent: function () {
var category = this.get('category');
var posts = this.get('model');
return category ? posts.filterBy('category', category) : posts;
}.property('category', 'model')
//Post-Category Component template
{{#link-to 'posts' (query-params category=staticCategory)}}
{{staticCategory}}
{{/link-to}}
//Post-Category Component js
Blog.PostCategoryComponent = Ember.Component.extend({
tagName: 'li',
isActive: function () {
return this.get('staticCategory') === this.get('currentCategory')
}.property('currentCategory', 'staticCategory'),
classNameBindings: ['isActive:active']
});
I've found a solution for this. Ember (currently) seems to make a distinction between linking to a resource and linking to a sub-route, e.g doing {{link-to "resource"}} will always set the active class, but doing {{link-to "resource.index"}} will toggle the active state according to their query params.
Here's a jsbin showcasing the difference: http://emberjs.jsbin.com/zawukucisoni/3/edit
I've opened an issue that can be found here: https://github.com/emberjs/ember.js/issues/5359

Ember.js: ArrayController undefined in template

Problem:
I am kind of struggling with the organization of my first ember app. The current issue is that the my Items ArrayController is not defined in my dashboard template:
<script type="text/x-handlebars" data-template-name="dashboard">
{{#if controllers.items}}
<p class="alert alert-error">Dashboard can access item's info - Nice!</p>
{{else}}
<p class="alert alert-error">Dashboard cannot access items... :-/</p>
{{/if}}
</script>
Likely cause: *
**EDIT: after talking with #conrad below, I'm kind of questioning this:*
I had a similar issue in an earlier post and kingpin2k suggested the cause was that I:
"never created anything that uses the options controller".
This is probably the case here as well. This quick screencast shows that a breakpoint on my ArrayController is not hit on page load - but it is hit when I inspect the Items controller in the Ember inspector tool (eg, Ember creates the ArrayController object right then for the first time).
Apparent non-solutions:
My Dashboard controller says it needs the Items controller. I guess that isn't enough to instantiate the ArrayController?
App.ItemsController = Ember.ArrayController.extend({
len: function(){
return this.get('length');
}.property('length'),
totalCost: function() {
return this.reduce( function(prevCost, item){
return parseInt(item.get('values').findBy('type', 'cost').price, 10) + prevCost;
}, 0);
}.property('#each.values')
[more computed properties...]
});
App.DashboardController = Em.Controller.extend({
needs: ['items'],
itemsLength: Ember.computed.alias('controllers.items.len'),
itemsTotalCost: Ember.computed.alias('controllers.items.totalCost'),
[more computed properties...]
});
Furthermore, each item in Items is being rendered in my items template. I guess that does not create the missing controllers.items either...
<script type="text/x-handlebars" data-template-name="items">
{{#each}}
[these render fine]
{{/each}}
</script>
<script type="text/x-handlebars" data-template-name="display">
<!-- DISPLAY TEMPLATE -->
{{!- DASHBOARD -}}
{{render dashboard}}
{{!- ITEMS -}}
{{render 'items' items}}
</script>
So then.. what?
I can imagine many possible avenues, but haven't gotten any of them to work yet:
Specify the Items ArrayController in {{render dashboard}}?
Some configuration in a Route?
Maybe my templates/routes are not correctly arranged?
You could make sure that the ItemController is instantiated in the dashboard template by calling it in the DashboardController's init function:
App.DashboardController = Em.Controller.extend({
needs: ['items'],
init: function() {
this._super();
this.get('controllers.items.length');
}
});
/edit:
removed the part that was not helpful