Ember select view controller based on content - ember.js

I currently have a view setup that renders the template depending on the model:
<ul>
{{#each controller.sortedAll}}
{{view App.ScoreView}}
{{/each}}
</ul>
.
App.ScoreView = Ember.View.extend({
templateName: function(){
var item = this.get('context')
if (item.sort < 8){
return 'low'
} else {
return 'high'
}
}.property(),
})
I'm struggling with assigning a specific controller for each separate view. The jsbin is: http://jsbin.com/tahag/5/edit
Is it possible to specify the controller in App.ScoreView using controller:? Or would I be better off trying to set an item controller:
{{view App.ScoreView itemController="VAL"}}
And pass the VAL from the parent controller as a property?

The controller is inherited from the current scope (defining itemController on the view won't do anything). You should do it on the each.
{{#each controller.sortedAll itemController='val'}}
{{view App.ScoreView}}
{{/each}}
Then within the view you can do this.get('controller')...
Also you can do an if statement and do {{render 'high' this}} if you want to have different types of controllers on each item.
{{#each controller.sortedAll}}
{{#if isBlue}}
{{render 'blue' this}}
{{/if}}
{{#if isGreen}}
{{render 'green' this}}
{{/if}}
{{/each}}
Personal recommendations:
To avoid making your template super convoluted I would just use a single controller.
{{#each controller.sortedAll itemController='score'}}
{{input value=sort}}
{{view App.ScoreView}}
{{/each}}
Add what the computed property is dependent on in order for it to automagically update:
App.ScoreView = Ember.View.extend({
templateName: function(){
var sort = this.get('controller.sort');
if (sort < 8){
return 'low';
} else {
return 'high';
}
}.property('controller.sort'),
});
Take advantage of the computed helpers
App.ScoreController = Ember.ObjectController.extend({
isVeryHigh: Em.computed.gt('sort', 20),
isVeryLow: Em.computed.lt('sort', 4)
});
Example: http://jsbin.com/sidebozi/1/edit

Related

Using computed property in Ember to get model data and display extra text

In my Ember template, I want to be able to loop over each item coming from the model (an array) and if the value is 'blue', display some text next to the value.
My template looks like this:
<script type="text/x-handlebars" data-template-name="index">
<h2>Loop over colors</h2>
<ul>
{{#each color in model}}
<li>{{color}} {{#if isBlue}} - Its Blue!{{/if}} </li>
{{/each}}
</ul>
</script>
And my app.js file looks like this:
App = Ember.Application.create({});
App.Router.map( function() {
this.resource( 'about');
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'blue'];
}
});
App.IndexController = Ember.ArrayController.extend({
isBlue: function() {
return this.get('content') == 'blue';
}.property()
});
I'm using this.get('content') because I thought that was supposed to be a reference to the actual model data.
I've tried numerous variations of the code but I'm now blocked. Hope someone can help.
You are defining the isBlue property on the IndexController, which is an ArrayController, and not on each item in the content. You can instruct the {{each}} helper to use an itemController for each item in the loop. By doing that you are able to define additional computed properties, that are not present in the original objects, and make them available within the each loop:
<script type="text/x-handlebars" data-template-name="index">
<h2>Loop over colors</h2>
<ul>
{{#each color in model itemController="color"}}
<li>{{color}} {{#if isBlue}} - Its Blue!{{/if}}</li>
{{/each}}
</ul>
</script>
App.ColorController = Ember.ObjectController.extend({
isBlue: function() {
return this.get('content') === 'blue';
}.property('content')
});
You can also check out JSBIN.
ArrayController means that the content property is an array, not just an object. Also, you don't want to access content directly. Controllers proxy their models, so use the controller as if it was an array. So your isBlue function is wrong in a few ways. It's probably possible to do what you want using the isBlue property, but I would use something like this:
colorItems: Em.computed.map('#this', function(color) {
return {
color: color,
isBlue: color === 'blue'
};
})
Then, in your template:
{{#each colorItems}}
<li>
{{color}}
{{#if isBlue}}
- It's Blue!
{{/if}}
</li>
{{/each}}

Ember template doesn't update after model update

http://jsbin.com/qoyudape/1/edit
Despite using .pushObject() template doesn't update. I've noticed it DOES update, if instead this I use model or content in template;
What is this in view is referring to if not model ? Is it possible to get it working using this and not model or content ?
var App = Ember.Application.create();
App.ApplicationRoute = Ember.Route.extend({
model: function(){
return Ember.A();
}
});
App.ApplicationController = Ember.ArrayController.extend({
actions: {
update: function(){
this.get("model").pushObject( Ember.Object.create({a:"b"}) );
console.log( this.get("model") );
}
}
});
template:
<script type="text/x-handlebars">
<button {{action "update"}}>update</button>
<br><br>
{{#if this}}
array not empty
{{else}}
array empty
{{/if}}
</script>
this is referring to the controller. btw, an easy way to find that out is to do {{log this}} in your template see also: http://emberjs.com/guides/understanding-ember/debugging/.
I'm not actually sure what it's checking to be truthy/falsy, but you can always just use length. I'll update once I find it.
{{#if this.length}}
array not empty
{{else}}
array empty
{{/if}}
http://jsbin.com/qoyudape/3/edit

How can I render a block only if a specific route is active?

I wanna render a block in Ember Handlebars only, if a specific route is active.
So, how can I create a 'ifRoute' helper, with the same conditons then the 'active' class on the 'linkTo' helper?
I want this, because I've a two layer navigation. So, I want to show the sub-navigation only, if the head navigation point is active. I dont wanna use the 'active' class, because I use lazy loading and I only want to load the sub navigation when the head navigation point is active.
So, what I want to do is:
<ul>
{{#each assortmentGroups}}
<li>
{{#linkTo "assortmentGroup" this}} {{description}} {{/linkTo}}
{{#ifRoute "assortmentGroup" this}}
<ul>
{{#each itemCategories}}
<li>{{#linkTo "itemCategory" this}} {{description}} {{/linkTo}}</li>
{{/each}}
</ul>
{{/ifRoute}}
</li>
{{/each}}
<ul>
How can I do this or is there a better solution?
Thanks
Just add to the controller:
needs: ['application'],
isCorrectRouteActive: Ember.computed.equal('controllers.application.currentRouteName', 'correctRoute')
Similarly:
isCorrectPathActive: Ember.computed.equal('controllers.application.currentPath', 'correct.path')
isCorrectURLActive: Ember.computed.equal('controllers.application.currentURL', 'correctURL')
I am quite sure latest Ember does the rest
Here are two possible options, although for both you first have to save the currentPath in your ApplicationController to have access to it whenever you need it:
var App = Ember.Application.create({
currentPath: ''
});
App.ApplicationController = Ember.ObjectController.extend({
updateCurrentPath: function() {
App.set('currentPath', this.get('currentPath'));
}.observes('currentPath')
});
Using a computed property
Then in the controller backing up the template, let's say you have a NavigationController you create the computed property and define also the dependency to the ApplicationController with the needs API to gather access, then in the CP you check if the currentPath is the one you want:
App.NavigationController = Ember.Controller.extend({
needs: 'application',
showSubMenu: function(){
var currentPath = this.get('controllers.application.currentPath');
return (currentPath === "assortmentGroup");
}.property('controllers.application.currentPath')
});
So you can use a simple {{#if}} helper in your template:
...
{{#linkTo "assortmentGroup" this}} {{description}} {{/linkTo}}
{{#if showSubMenu}}
<ul>
{{#each itemCategories}}
<li>{{#linkTo "itemCategory" this}} {{description}} {{/linkTo}}</li>
{{/each}}
</ul>
{{/if}}
</li>
...
Using a custom '{{#ifRoute}}' helper
But if your really want a custom helper to deal with your condition then this is how you could do it, note that the currentPath stored on your application is still needed since we need a way to get the value of the current route:
Ember.Handlebars.registerHelper('ifRoute', function(value, options) {
if (value === App.get('currentPath')) {
return options.fn(this);
}
else {
return options.inverse(this);
}
});
And then you could use it like this:
...
{{#linkTo "assortmentGroup" this}} {{description}} {{/linkTo}}
{{#ifRoute "assortmentGroup"}}
<ul>
{{#each itemCategories}}
<li>{{#linkTo "itemCategory" this}} {{description}} {{/linkTo}}</li>
{{/each}}
</ul>
{{/ifRoute}}
</li>
...
See here also a simple Demo of the "custom helper" solution: http://jsbin.com/izurix/7/edit
Note: with the second solution there is a catch! Since bound helpers do not support blocks (in embers handlebars customization) I used a simple helper that does not reevaluate the condition depending on bindings which is may not what you want.
Hope it helps.
After investigating the ember code for the linkTo and if helpers, the answer from intuitivepixel and a blog post about writing my own bound block helper, I've found a solution:
var resolveParams = Ember.Router.resolveParams;
var resolvedPaths = function(options) {
var types = options.options.types.slice(1),
data = options.options.data;
return resolveParams(options.context, options.params, { types: types, data: data });
};
Ember.Handlebars.registerHelper('ifRoute', function(name) {
var options = [].slice.call(arguments, -1)[0];
var params = [].slice.call(arguments, 1, -1);
var theResolvedPaths = resolvedPaths({ context: this, options: options, params: params });
var router = options.data.keywords.controller.container.lookup('router:main');
var self = this;
var evaluateIsCurrentRoute = function() {
self.set('current_route_is_active_bool_for_ifroute', (function() {
return router.isActive.apply(router, [name].concat(theResolvedPaths)) ||
router.isActive.apply(router, [(name + '.index')].concat(theResolvedPaths));
})());
};
evaluateIsCurrentRoute();
router.addObserver('url', evaluateIsCurrentRoute);
options.contexts = null;
return Ember.Handlebars.helpers.boundIf.call(this, 'current_route_is_active_bool_for_ifroute', options);
});
I found an easy way to check if a route is active, but to get this into a computed property may not be so easy.
// Test if you are currently in a route by it's lowercase name
App.isInRoute = function(name) {
return App.Router.router.currentHandlerInfos.mapProperty('name').contains(name);
}
To use:
App.isInRoute('posts.show'); // true if in the route

How to retrieve model properties from an ember view, which was created inside an {{#each}}

I'm having an issue retrieving properties from my model inside a view that was created from a template inside an {{#each}} loop for an array controller. Here is the snippet:
{{#each controller}}
{{view MyApp.MyView}}
{{/each}}
MyApp.MyView = Ember.View.extend({
didInsertElement: function() {
var property = this.get('controller.property');
console.log(property); // Outputs "undefined"
}
});
When I've used this.get('controller.property'); in the past, it has worked. However, now that I am using an ArrayController it does not seem to be working. Is there a way that I can access the current properties from the each loop inside the view code?
You can pass the current item of the each helper, to the content property of the view, using the this keyword:
{{#each controller}}
{{view MyApp.MyView contentBinding="this"}}
{{/each}}
MyApp.MyView = Ember.View.extend({
didInsertElement: function() {
var someObject = this.get('content');
console.log(someObject);
}
});
You can do this, I think:
{{#each controller}}
{{view MyApp.MyView}}
{{/each}}
MyApp.MyView = Ember.View.extend({
didInsertElement: function() {
var someObject = this.get('parentView.controller');
console.log(someObject);
}
});

What is the best way to handle events in Ember.js?

I'm beginning to learn Ember and it's not clear what the best, most acceptable, or even intended method to handle events is. Is it acceptable to check the target in the click functions event argument, should I make a new view for each item that requires an event other than {{action}}, or something totally different?
IMO you should use the {{action}} helper where possible. If you want to attach events on a tag in the template, use {{action}}; no need to make a new View:
<a {{action showPosts href=true}}>All Posts</a>
<form {{action validate target="controller"}}>
// ...
</form>
An exception to the above is when you want to handle more than one events on a specific element:
// Template
<ul>
{{#each post in controller}}
{{#view App.PostView}}
{{title}}
{{#if view.showDetails}}
<span>{{summary}}</span>
{{/if}}
{{/view}}
{{/each}}
</ul>
// View
App.PostView = Ember.View.extend({
tagName: li,
classNames: ['post-item'],
mouseEnter: function(event) {
this.set('showDetails', true);
},
mouseLeave: function(event) {
this.set('showDetails', false);
}
});
As we need to capture both mouseEnter and mouseLeave (to show and hide the details of the post respectively), it is better to do it in the View, avoiding too much logic in the templates. The alternative way for the above would be to use as many nested tags as the number of events we want to handle (in our case, 2):
// Template
<ul>
{{#each post in controller}}
<li class="post-item" {{action showTheDetails post on="mouseEnter" target="controller"}}>
<span class="dummy" {{action hideTheDetails post on="mouseLeave" target="controller"}}
{{title}}
{{#if post.showDetails}}
<span>{{summary}}</span>
{{/if}}
</span<
</li>
{{/each}}
</ul>
And then in the controller:
// Controller
App.PostsController = Ember.ArrayController.extend({
showTheDetails: function(event) {
var post = event.context;
post.set('showDetails', true);
},
hideTheDetails: function(event) {
var post = event.context;
post.set('showDetails', false);
}
});
But I think you will agree that this is uglier. See here.
In cases where you want to use Ember control views (Ember.TextField, Ember.TextArea, etc.) you have no choice but to capture events in the View. So you extend the control view and define the event handlers in the View:
// Template
<legend>Add a comment</legend>
{{view App.CommentInputField valueBinding="comment"}}
// View
App.CommentInputField = Ember.TextField.extend({
focusOut: function(event) {
this.get('controller').validateComment();
},
keyDown: function(event) {
if (event.keyCode === 13) { // Enter key
this.get('controller').createComment();
return false;
}
}
});