ember.js: using routes, templates and outlets to render model data - ember.js

I'm going round in circles here, trying to pull all the components together to produce the desired view. I feel as if I just need to just tweak the dial to bring it all into focus but at the moment it aludes me.
I have two models - Person and Address - which I have created two templates for; I then want to render these two templates in another 'main' template. At the moment I am not linking them in anyway (eventually 1 person will have many nested addresses) because I want to understand the general principes first.
The two templates work individually using App.Router.map
this.resource('listOfPeopleTemplate', { path: '/' });
or
this.resource('listOfAddressesTemplate', { path: '/' });
but not together or when I add the mainViewTemplate and try to add both into that:
App.Router.map(function () {
//this.resource('listOfAddressesTemplate', { path: '/' });
//this.resource('listOfPeopleTemplate', { path: '/' });
this.resource('mainViewTemplate', { path: '/' });
});
The problem seems centered around:
App.MainViewTemplateRoute = Ember.Route.extend({
renderTemplate: function() {
this.render('listOfPeopleTemplate', {into: 'mainViewTemplate', outlet: 'peops'});
this.render('listOfAddressesTemplate', {into: 'mainViewTemplate', outlet: 'address'});
}
});
Errors returned are "outlet (people) was specified but not found"; and "The value that #each loops over must be an Array..". I can see that I may need to do something about the controller for both the Addresses and People but I don't know what. Fact is, i've got myself into such a muddle I now can't even get the originally successfull version working (with either the address or people displaying in their own template).
I have made the following fiddle http://jsfiddle.net/4gQYs/4/. Please, bring me into focus!

I hope I understood your problem!
I have two routes people and places.
App.Router.map(function(){
this.resource('people');
this.resource('places');
});
I am loading the model for both the controller in model hook of people route.
App.PeopleRoute=Ember.Route.extend({
model:function(){
var places=Em.A();
$.getJSON("js/places.js").then(function(json){places.setObjects(json)});
var placesController=this.generateController('places',places);
placesController.set('content',places);
var people=Em.A();
$.getJSON("js/people.js").then(function(json){people.setObjects(json)});
return people;
},
renderTemplate:function(){
this.render('people',{into:"application",outlet:"people"});
this.render('places',{into:"application",outlet:"places"});
}
});
The following is not needed.May be useful in displaying some related data.
App.PeopleController=Ember.ArrayController.extend({
needs:'places'
});
Now I am rendering the two templates in main application template.
<script type="text/x-handlebars">
<h2>Welcome to Ember.js</h2>
{{outlet people}}
{{outlet places}}
</script>
<script type="text/x-handlebars" data-template-name="people">
{{#each controller}}
<p>{{name}}</p>
{{/each}}
</script>
<script type="text/x-handlebars" data-template-name="places">
{{#each controller}}
<p>{{name}}</p>
{{/each}}
</script>

Related

Ember.js Multiple Models for a Modal Dialog Box

I am new to Ember.js, and I am building a web application that is using Ember.js and Ember-Data for its front-end technology. I am trying to understand what would be the best practice for when you might have multiple ember-data bound components on a page that use an independent model.
Here is kind of what I'm trying to do:
https://gist.github.com/redrobot5050/6e775f4c5be221cd3c42
(There's a link on the page to editing it within jsbin this gist. For some reason, I can't get a 'Share' URL off the vanity URL.)
I have a template like so:
<script type="text/x-handlebars" data-template-name="index">
<p>Options for graphics quality: </p>
<ul>
{{#each item in model}}
<li>{{item.setting}}</li>
{{/each}}
</ul>
<p>Currently Selected: {{model.selectedValue}}</p>
<p>Draw Distance Options:</p>
<ul>
{{#each item in dropdown}}
<li>{{item.distance}}
{{/each}}
</ul>
<p>Currently Selected Distance: {{selectedDistance}}
</p>
{{outlet}}
<button {{action 'openModal' 'modal' model}}>Change Settings</button>
</script>
In this template, all the data binds correctly and appears in scope. However, when I attempt to modify it within its modal dialog box, only Quality is bound to its Ember.Select view. I have attempted to force the binding in the IndexController with a controller.set but it does not appear to be working.
My IndexController looks like this:
App.IndexRoute = Ember.Route.extend({
model: function() {
var qualityList = this.store.find('quality');
console.log('qualityList=' + qualityList);
return qualityList;
//return App.Quality.FIXTURES;
},
setupController : function(controller, model) {
controller.set('model', model);
var drawDistanceList = this.store.find('drawDistance');
console.log('distanceList=' + drawDistanceList );
controller.set('dropdown', drawDistanceList);
controller.set('selectedDistance', 1);
//this.controllerFor('modal').set('dropdown', drawDistanceList );
}
});
The JSBin really shows off what I am attempting to do: I want to load/bind each of the drop downs independently from the same controller. The JSBin does not work correctly because I'm not really sure how to do this, just yet. I am posting to stackExchange to see if someone can modify this JSBin and show me what I'm doing wrong, or if someone can point me in the right direction, design-wise on how to solve this problem?
(For example, I think a possible solution could be to create the dropdowns as components, and load the data through their controller or pass it in as properties from the parent controller, but I really want to know what is the "The Ember Way").
App.IndexRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
qualityList: this.store.find('quality'),
drawDistanceList: this.store.find('drawDistance')
});
},
setupController: function(controller, model) {
controller.set('model', model.qualityList);
controller.set('dropdown', model.drawDistanceList);
}
});
Documentation for Ember.RSVP.hash used to be here: http://emberjs.com/api/classes/Ember.RSVP.html#method_hash. I'm not sure why it has disappeared.
For the moment, you can find it at: http://web.archive.org/web/20140718075313/http://emberjs.com/api/classes/Ember.RSVP.html#method_hash

Inheriting singular controller with render helper

I am trying to render a set of tabs for a set of objects (conversations) using the render helper for each. This is not part of a route as it is a persistent part of the interface. I have run into a problem where only the view with the same name as the model gets the intended controller (i.e. the panel contents and not the tab headers).
I have a Chat model, object controller and array controller (deliberately simplified here):
App.Chat = DS.Model.extend({ });
App.ChatsController = Ember.ArrayController.extend({
needs: 'application',
content: Ember.computed.alias('controllers.application.currentChats'),
});
App.ChatController = Ember.ObjectController.extend({ });
The ArrayController needed the needs/content properties because the chats are loaded in the application controller. I used the currentChats name as other routes may load non-current chats.
App.ApplicationController = Ember.Controller.extend({
init: function(){
this.store.find('chat', {"current": true});
this.set('currentChats', this.store.all('chat'));
}
});
I have no difficulty rendering the chat contents with the appropriate controller (into the 'chat' template). However, the chat tabs are given the default ObjectController, and therefore can't fire actions.
<script type="text/x-handlebars" id="application">
<!--application template-->
{{outlet chats}}
</script>
<script type="text/x-handlebars" id="chats">
<div id="chats">
<ul id="chat-tabs">
{{#each}}
{{render 'chatTab' this}}
{{/each}}
</ul>
{{#each}}
{{render 'chat' this}}
{{/each}}
</div>
</script>
<script type="text/x-handlebars" id="chatTab">
<!--tab template-->
</script>
<script type="text/x-handlebars" id="chat">
<!--chat template-->
</script>
The application router is as follows:
App.ApplicationRoute = Ember.Route.extend({
model: function(){ },
renderTemplate: function(){
this.render('application', { });
this.render('chats', {
into: 'application',
outlet: 'chats',
controller: 'chats'
});
}
});
This seems to come solely down to naming of the templates. The template called 'chat' inherits the correct controller, but chatTab doesn't despite receiving a chat as the model. Is there any way to force the view to inherit the correct controller? Or am I going about this in an idiosyncratic way.
Many thanks for your help to this Ember novice.
Andrew
It goes solely off the name provided to the render. The easiest way is to just create the other controller and extend the chat controller.
App.ChatTabController = App.ChatController.extend();

Ember.js: how to use an ArrayController to describe multiple models?

I am trying to set up a dashboard that can monitor and display information on multiple models. The ArrayController seems like the correct object to use, but I am not sure what I am doing wrong.
Can someone explain where I've gone astray here?
jsBin Example: http://jsbin.com/IgoJiWi/8/edit?html,js,output
javascript:
App = Ember.Application.create();
/* ROUTES */
App.Router.map(function() {
this.resource('options');
this.resource('dashboard');
});
App.IndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('options');
}
});
App.OptionsRoute = Ember.Route.extend({
model: function() {
var a = Em.A();
a.pushObject( App.Options.create({title: 'A', cost: '100'}));
a.pushObject( App.Options.create({title: 'B', cost: '200'}));
a.pushObject( App.Options.create({title: 'C', cost: '300'}));
return a;
}
});
/* MODELS */
App.Options = Ember.Object.extend({
title: '',
cost: '',
quantity: ''
});
/* CONTROLLERS */
App.optionsController = Ember.ArrayController.extend({
legend: 'test',
len: this.length,
totalCost: function() {
return this.reduce( function(prevCost, cost, i, enumerable){
return prevCost + cost;
});
}.property('#each.cost')
});
handlebars:
<script type="text/x-handlebars" data-template-name="application">
<p><strong>Ember.js example</strong><br>Using an ArrayController to access aggrigated data for all models of type X.</p>
{{render dashboard}}
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="options">
<h2>Options:</h2>
<dl>
{{#each}}
<dt>Title: {{title}}</dt>
<dd>Cost: {{cost}} {{input value=cost}}</dd>
{{/each}}
</dl>
</script>
<script type="text/x-handlebars" data-template-name="dashboard">
<h2>Overview:</h2>
<p>Why won't this display info about the options below? I suspect that the optionsController does not actually contain options A-C...</p>
{{#with App.optionsController}}
<p>Total number of options (expect 3): {{len}}</p>
<p>Total cost of options (expect 600): {{totalCost}}</p>
{{/with}}
</script>
Without getting into the why of doing things this way, there were a couple problems with making it just work.
optionsController needs to be OptionsController
the active controller in the dashboard will be DashboardController (autogenerated if not defined) so you need to open that and give it a reference to options
in reduce, the second argument is an item reference, so you need to do get('cost') on it
in order for javascript to know you want integer math, you need to use parseInt
This is a working jsbin: http://jsbin.com/acazAjeW/1/edit
lol, kingpin2k and I seem to be competing for answering ember questions these days.
Part of the problem is, your dashboard exists even when the options may not, which might be the route you are going in the future, here's a partial version that works, I'll look into the other version.
http://jsbin.com/ImOJEJej/1/edit
Using render
http://jsbin.com/ImOJEJej/3/edit

Ember does not render after transition

I have just written extremly simple Ember app, built on top of the Rails app, working with Ember Data and displaying, creating and persisting just one entity type to the server. Everything with the latest tools (Ember v1.0.0-pre.4-134-gaafb5eb).
However, there is very strange problem I have encountered. My app has two views: entity list (index) and form for creating new entities. When I enter the index directly, everything displays OK. But when I go to the other view and then back to the list, the view is not rendered again. Where could be the problem?
I guess it might be caused by my (maybe incorrect) using new Ember router. So I'm pasting important (from my point of view) parts of the app here:
Router:
App.Router.map(function() {
this.resource('bands', function() {
this.route('new');
});
});
App.IndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('bands');
}
});
App.BandsRoute = Ember.Route.extend({
model: function() {
return App.Band.find();
}
});
App.BandsNewRoute = Ember.Route.extend({
renderTemplate : function(){
this.render('bands_new',{
into:'application'
});
}
});
Link back to list - which does not work:
App.BandsNewController = Em.ArrayController.extend({
cancel: function() {
this.transitionTo('bands');
}
});
Have a look at the whole app here: https://github.com/pavelsmolka/roommating
(It's hugely inspired by great https://github.com/dgeb/ember_data_example)
I don't believe it, but could it be bug in Ember itself?
I think your "render" call in your BandsNewRoute is messing things up.Try making things go more with Ember defaults. So I would refactor your app to do this:
(working fiddle: http://jsfiddle.net/andremalan/DVbUY/)
Instead of making your own render, all you need to do is create a "bands" template (it can be completely empty except for {{outlet}} if you want) and a "bands.index" template.
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="bands/index">
<h2>Bands Index</h2>
{{#linkTo bands.new}}New Band{{/linkTo}}
</script>
<script type="text/x-handlebars" data-template-name="bands">
<h1>Bands</h1>
<p>
{{#linkTo index}}Start Again{{/linkTo}}
{{#linkTo bands.new}}New Band{{/linkTo}}
</p>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="bands/new">
I'm in new band!
<a {{action "cancel"}}>Cancel</a>
</script>
Your routes also clean up really nicely this way:
App.Router.map(function() {
this.resource('bands', function() {
this.route('new');
});
});
App.IndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('bands');
}
});
App.BandsNewController = Ember.Controller.extend({
cancel: function() {
this.transitionTo('bands');
}
});
I hope that helps!

Ember.js router v2 App.Router.map inconsistent in documentation?

I'm creating an app with ember.js. I started on PRE.2 but ended up using ember-data v11 so upgraded to master for ember proper. This meant having to change to the new v2 router interface (which as a side note I think is so much better, so thank you.)
I'm having a couple of problems trying to figure out how it works, I'm deep in the guide but there are a couple of inconsistencies I can't quite get my head around:
1)
It seems there are two different conventions used to configure the route map:
In the 'Templates' section, a match().to() interface is used
App.Router.map(function(match) {
match('/').to('index');
match('/posts').to('posts');
match('/posts/:post_id').to('post');
});
( this method is also used in Tom Dale's gist )
In the 'Routing' section, a resource / route interface is used:
App.Router.map(function() {
this.resource('posts', function() {
this.route('new');
});
});
Here it states that a "resource" should be used for noun routes, and "route" for verb routes.
Then in the "Redirecting to a different URL" section, this noun/verb convention isn't followed:
App.Router.map(function(match) {
this.resource('topCharts', function() {
this.route('choose', { path: '/' });
this.route('albums');
this.route('songs');
this.route('artists');
this.route('playlists');
});
});
My first question is:
Going forward, what is the proper convention for creating routes?
My second question follows on from that and is more relevant to my application:
How do I link from a top level "resource" route to a nested "route" route and pass through the appropriate models?
( there is an example of this in the 'Links' section of the 'Templates' doc, but it pertains to the match().to() interface, and I'm specifically working with the resource/route interface )
Here's my example:
I have created a simple site structure based on streams, a stream consists of details, a set of posts, handles and history. My routing is set up like so:
App.Router.map(function() {
this.resource('streams');
this.resource('stream', { path: '/stream/:stream_id' }, function(){
this.route('details');
this.route('posts');
this.route('handles');
this.route('history');
});
});
My streams route looks like this:
App.StreamsRoute = Ember.Route.extend({
model: function() {
return App.Stream.find();
},
setupController: function(controller, model) {
controller.set('content', model);
}
});
and the template:
<script type="text/x-handlebars" data-template-name="streams">
<ul>
{{#each stream in controller}}
<li>{{#linkTo "stream" stream}} {{stream.title}} {{/linkTo}}</li>
{{/each}}
</ul>
</script>
My stream (singular) route:
<script type="text/x-handlebars" data-template-name="stream">
<nav>
{{#linkTo "stream.details" }}Details{{/linkTo}}
</nav>
{{outlet}}
</script>
Now, I'd like to link to my sub route "details", but I'm not sure what to place in the linkTo so that my model (which is a stream) is passed down into this sub-route:
App.StreamDetailsRoute = Ember.Route.extend({ });
My "details" template just displays some attributes off the stream object.
<script type="text/x-handlebars" data-template-name="stream/details">
<h2>Stream Details</h2>
<p>Id: {{id}}</p>
<p>Title: {{title}}</p>
</script>
I will also want to link through to posts, history and handles sub-routes and be able to display these aggregations based on the stream model. I'm not sure exactly how to do this. I assume I need to use setupController to get the items to display, I'm just not sure how to get the stream object down into these sub routes.
Going forward, what is the proper convention for creating routes?
The Resource/Route approach as described in http://emberjs.com/guides/routing/defining-your-routes/
How do I link from a top level "resource" route to a nested "route" route and pass through the appropriate models?
Specify the name of a route as the first parameter, followed by any contexts that are required. So in your example, when creating a link to "stream.details" from the stream template you need to specify this as the context.
{{#linkTo "stream.details" this}}Details{{/linkTo}}
The approach described in http://emberjs.com/guides/templates/links/ still covers the basics.
When in doubt I recommend checking the test cases for link_helper. For example: https://github.com/emberjs/ember.js/blob/master/packages/ember/tests/helpers/link_to_test.js#L249