Computed.alias not updating bind-attr - javascript

I recently started using Ember.js. In my small application I currently have problems regarding Ember.computed.alias, because an {{#if}}-section is updated properly, but the bind-attr helper in the same template is not updated accordingly.
The application controller and the action influencing the value look as follows:
App.ApplicationController = Ember.ObjectController.extend({
isEditing: false,
actions: {
toggleEdit: function() {
var a = this.get('isEditing');
this.set('isEditing', !a);
}
}
});
The controller taking care of the template causing problems:
App.CategoriesController = Ember.ArrayController.extend({
needs: ['application'],
isEditing: Ember.computed.alias('controllers.application.isEditing'),
general: function() { // example depending on the alias
var result = this.filterBy('type', 1);
if (!this.get('isEditing')) {
result = result.filterBy('isHidden', false);
}
return result;
}.property('#each.type', '#each.isHidden', 'isEditing'),
// ......
The related template:
<ul id="categories">
{{#if isEditing}}YES!{{else}}NO!{{/if}}
{{#each general}}
<li {{bind-attr class=":general isEditing:editing"}}>
{{name}}
</li>
{{/each}}
</ul>
When the action toggleEdit is triggered, the {{#if}} section is updated and swaps between YES! and NO!, but the editing class is not applied to the list element. I tried encapsulated the alias into another property of the controller depending on the alias, but without success.
I assume it's a beginners mistake, but I can't figure out what I am overlooking.
Thanking you in anticipation.

isEditing is no longer in scope, use controller.isEditing, sorry phone response
Here's an example that would keep it in scope, but I'm fully qualifying it just to show you.
{{#each item in general}}
<li {{bind-attr class=":general controller.isEditing:editing"}}>
{{item.name}}
</li>
{{/each}}

Related

Ember and Handlebars Iterate Over a Set Array

I'm working on learning Ember and am trying to do some small ideas with it. Currently, I am trying to receive text field input to filter a list and return the matching results. I have all of this working, you know, the 'hard' stuff. However, the part that isn't working is Handlebars reading the 'title' property of my array that I am returning. It's just blank.
Here is my template:
<script data-template-name="application" type="text/x-handlebars">
{{input type="text" value=searchString placeholder="Search..."}}
{{filterMovies}}
<ul>
{{#each searchResults}}
<li>{{title}}</li>
{{/each}}
</ul>
</script>
And now my controller:
App.ApplicationController = Ember.Controller.extend({
filterMovies: function() {
var self = this,
searchString = self.get('searchString'),
searchResults = [],
filterArrLength = null,
theFullMovieList,
theFilteredMovieList = [];
if (!searchString) {
return;
}
var url = 'http://www.json-generator.com/api/json/get/clVKyWQSnC';
Ember.$.getJSON(url).then(function(data) {
theFullMovieList = data;
theFullMovieList.filter(function(movie) {
if (movie.title.toLowerCase().startsWith(searchString)) {
theFilteredMovieList.push(movie);
}
});
console.log(theFilteredMovieList);
self.set('searchResults', theFilteredMovieList);
});
}.property('searchString')
});
I have tried printing using {{this}}, {{this.title}}, {{searchResults.title}}, and {{title}} with no luck. However, logging the array shows the correct values.
Any ideas? View On CodePen
Your each syntax is invalid. You have to use new syntax:
<ul>
{{#each searchResults as |movie|}}
<li>{{movie.title}}</li>
{{/each}}
</ul>
See working demo on CodePen.

Ember.js route problems with filter

My aim is to pass filtered data to my controller and then to my template. I've tried not using the filter and everything works as expected. If I even try to use a filter that lets everything through, I don't get any data. I've even tried using false instead of true and fiddling with the argument list of the filter.
I'm using ember-data fixtures to test this. I'm following the name conventions so much of the work is done for me under the hood. That all seems to be working though (otherwise the first example should also have a problem).
Works (arrives in the controller and eventually gets rendered on the page):
App.DomainDirRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('domain_dir');
}
});
Fails (controller gets an empty array):
App.DomainDirRoute = Ember.Route.extend({
model: function(params) {
return this.store.filter('domain_dir', function(item){
return true;
});
}
});
UPDATE (ATTEMPT 1):
Okay, so I've tried a couple of things based on Sam Selikoff's answer. I've defined 4 properties (2 filters, one map, one plain copy) in the controller and tried to display each in the mockup page. Only the property copyDomain gives a result.
Properties in controller:
filteredDomains: Ember.computed.filterBy('domain', 'domain', true),
upperCaseDomains: Ember.computed.map('domain', function(domain, index) {
return domain.toUpperCase() + '!';
}),
filteredDomains2: function() {
return this.get("model").filterBy('domain', true);
}.property('model.#each.domain'),
copyDomains: function(){
result = [];
this.forEach(function(item) {
result.pushObject(item);
})
console.log(result);
return result;
}.property('model.#each.domain')
Mockup:
<ul>
<li>filteredDomains</li>
{{#each domainDir in controller.filteredDomains}}
<li>domainDir.domain</li>
{{/each}}
</ul>
<ul>
<li>filteredDomains2</li>
{{#each domainDir in controller.filteredDomains2}}
<li>domainDir.domain</li>
{{/each}}
</ul>
<ul>
<li>upperCaseDomains</li>
{{#each domainDir in controller.upperCaseDomains}}
<li>domainDir.domain</li>
{{/each}}
</ul>
<ul>
<li>copyDomains</li>
{{#each domainDir in controller.copyDomains}}
<li>domainDir.domain</li>
{{/each}}
</ul>
Filtering is generally done at the controller/component level. store.find makes an AJAX request. Is your goal to only retrieve the filtered subset of data from the server, or to filter the data you already have at the view layer?
Typically if you're just wanting to do some live filtering, you'll do it in the controller. Leave your model hook as this.store.find('domain_dir') and add a filter in your controller:
App.DomainDirController = Ember.Controller.extend({
filteredDomains: function() {
return this.get("model").filterBy('someProp', true);
}.property('model.#each.someProp')
});
You should also check out the computed macros for some shorthands:
App.DomainDirController = Ember.Controller.extend({
filteredDomains: Ember.computed.filterBy('model', 'someProp');
});
Now in your template, you can do
{{#each domain in filteredDomains}}
...

How to create a multiselect list in Ember.js

I'm trying to figure out how to build a small app consisting of a list where you can select multiple items and toggle to select all/none and see the number of currently selected rows.
I believe that the "selected" state should not be part of the model objects, but I cannot really figure out how to do it.
This is my current setup (which doesn't work obviously yet)
Runnable code http://jsfiddle.net/jacobk/rU35G/1/
var App = Ember.Application.create();
App.ApplicationRoute = Ember.Route.extend({
model: function() { return Ember.A(["Foo", "Bar", "Baz"]); }
});
App.ApplicationController = Ember.ArrayController.extend({
allSelected: false,
selectedCount: function() {
return 0;
}.property()
});
App.RowController = Ember.ObjectController.extend({
isSelected: false
});
<script type="text/x-handlebars" data-template-name="application">
<h3>{{ selectedCount }} rows selected.</h3>
<label>
{{view Ember.Checkbox checkedBinding="allSelected"}}
Toggle select all
</label>
<hr/>
<ul>
{{#each controller itemController="row"}}
<li {{bindAttr class="isSelected"}}>
{{view Ember.Checkbox checkedBinding="isSelected"}} {{this.content}}
</li>
{{/each}}
</ul>
</script>
Should the individual "row items" be controlled using a custom view per row, or a custom controller like in the fiddle above
How to propagate the "select all" from the ArrayController to all the individual controllers (or views if that's a better fit)
I'm trying to understand when to use bindings, observers, properties, "needs" etc. and when its appropriate to use controllers vs views and so on. I've yet to grok the general flow of information/data in ember apps.
e.g. should the ArrayController from my example above iterate over the "contained" views/controllers and change the "selected" state when the "select all" check box is toggled OR should all the "sub controllers" observe/"have bindings to" the ArrayController and change themselves when it changes, and if so, how should I propagate data the opposite direction. How would the ArrayController get "all currently selected" rows?
I would love to see the "canonical solution" for this.
No need of row controller. #each, computed property and checkedbinding can be utilized to solve this as shown below. isSelected has to be defined in content of the arraycontroller:
App.ApplicationController = Ember.ArrayController.extend({
allSelected: function(key, value) {
if ( value !== undefined ) {
// when check box is ticked, this gets executed
this.setEach( 'isSelected', value );
return value;
} else {
//as a computed property
return !!this.get( 'length' ) &&
this.everyProperty( 'isSelected', true );
}
}.property('#each.isSelected')
selectedCount: function() {
return 0;
}.property()
});
I agree about keeping the selected state out of the model. You need to define the itemController in the Ember.ArrayController.
here is a working example. http://jsbin.com/sunat/3/edit
App.RowController = Ember.ObjectController.extend({
isSelected: false
});
App.IndexController = Ember.ArrayController.extend({
itemController: 'row',
selectAll: function(key, value) {
if (arguments.length == 2) {
this.setEach('isSelected', value);
return value;
} else {
return this.isEvery('isSelected', true);
}
}.property('#each.isSelected')
});
#template
<script type="text/x-handlebars" id="index" >
<label>
{{input type="checkbox" checked=selectAll}}
Toggle select all
</label>
<hr/>
<ul>
{{#each}}
<li>
{{input type="checkbox" checked=isSelected}} {{name}}
</li>
{{/each}}
</ul>
</script>

handlebars - is it possible to access parent context in a partial?

I've got a handlebar template that loads a partial for a sub-element.
I would need to access a variable from the parent context in the calling template, from within the partial. .. doesn't seem to resolve to anything inside the partial.
Simplified code goes like this:
the template
{{#each items}}
{{> item-template}}
{{/each}}
the partial
value is {{value}}
(obviously the real code is more complicated but it's the same principle, within the partial .. appears to be undefined.)
To show it's undefined, I've used a very simple helper whatis like this:
Handlebars.registerHelper('whatis', function(param) {
console.log(param);
});
and updated the above code to this:
updated template
{{#each items}}
{{whatis ..}} <-- Console shows the correct parent context
{{> item-template}}
{{/each}}
updated partial
{{whatis ..}} <-- Console shows "undefined"
value is {{value}}
Is there a way to go around that issue? Am I missing something?
EDIT: There's an open issue relating to this question on handlebars' github project
Just in case anyone stumbles across this question. This functionality exists now in Handlebars.
Do this:
{{#each items}}
{{! Will pass the current item in items to your partial }}
{{> item-template this}}
{{/each}}
Working fiddle (inspired by handlebars pull request #385 by AndrewHenderson)
http://jsfiddle.net/QV9em/4/
Handlebars.registerHelper('include', function(options) {
var context = {},
mergeContext = function(obj) {
for(var k in obj)context[k]=obj[k];
};
mergeContext(this);
mergeContext(options.hash);
return options.fn(context);
});
Here's how you'd setup the parent template:
{{#each items}}
{{#include parent=..}}
{{> item-template}}
{{/include}}
{{/each}}
And the partial:
value is {{parent}}
As of 2.0.0 partials now supports passing in values.
{{#each items}}
{{> item-template some_parent_var=../some_parent_var}}
{{/each}}
Took me awhile to find this, hope it's useful for someone else too!
The easiest way to pass the parent context to the partial is to do the loop inside the partial. This way the parent context is passed by default and when you do the loop inside the partial the {{../variable}} convention can access the parent context.
example fiddle here.
The Data
{
color: "#000"
items: [
{ title: "title one" },
{ title: "title two" },
]
}
The Template
<div class="mainTemplate">
Parent Color: {{color}}
{{> partial}}
</div>
The Partial
<div>
{{#each items}}
<div style="color:{{../color}}">
{{title}}
</div>
{{/each}}
</div>
You can use some of the proposed solutions on the comments from the link to github:
https://github.com/wycats/handlebars.js/issues/182#issuecomment-4206666
https://github.com/wycats/handlebars.js/issues/182#issuecomment-4445747
They create helpers to pass the info to the partial.
I created an each Helper function that includes the parent key/values within the subcontext under the key parentContext.
http://jsfiddle.net/AndrewHenderson/kQZpu/1/
Note: Underscore is a dependency.
Handlebars.registerHelper('eachIncludeParent', function ( context, options ) {
var fn = options.fn,
inverse = options.inverse,
ret = "",
_context = [];
$.each(context, function (index, object) {
var _object = $.extend({}, object);
_context.push(_object);
});
if ( _context && _context.length > 0 ) {
for ( var i = 0, j = _context.length; i < j; i++ ) {
_context[i]["parentContext"] = options.hash.parent;
ret = ret + fn(_context[i]);
}
} else {
ret = inverse(this);
}
return ret;
});
To be used as follows:
{{#eachIncludeParent context parent=this}}
{{> yourPartial}}
{{/eachIncludeParent}}
Access parent context values in your partial using {{parentContext.value}}
I needed dynamic form attributes for something like this...
{{#each model.questions}}
<h3>{{text}}</h3>
{{#each answers}}
{{formbuilder ../type id ../id text}}
{{/each}}
{{/each}}
and a helper like so...
Handlebars.registerHelper('formbuilder', function(type, id, qnum, text, options)
{
var q_type = options.contexts[0][type],
a_id = options.contexts[1].id,
q_number = options.contexts[0][qnum],
a_text = options.contexts[1].text;
return new Handlebars.SafeString(
'<input type=' + q_type + ' id=' + a_id + ' name=' + q_number + '>' + a_text + '</input><br/>'
);
});
Which produces...
<input type="checkbox" id="1" name="surveyQ0">First question</input>
My model is a big blob of arrays and objects mixed together. What's noteworthy is that using '../' like so '../type', passes in the parent model as the context, and without it, such as with 'id', it passes in the current model as the context.
To get specifically the parent of the partial (where you may be several partials deep) then follow the other answers like SeanWM.
If you know that the parent is the main template then you can use #root which resolves to the top-most context no matter how deep you are.
e.g. {{#root.rootObject.rootProperty}}
It is a pity that ../../.. does not go up past a partial.

How to pass parameters with the action Helper of Ember.js?

I have a list of items:
<ul>
{{#each applications}}
<li>
<a {{bindAttr href="url"}}
{{action "appClicked" on="click"}}>
{{name}}
</a>
</li>
{{/each}}
</ul>
On click it calls the method appClicked of the view, that this template belongs to. I want to pass some information (for example, the name of the application) to the method appClicked. Something like, {{action "appClicked(name)" on="click"}}.
Is it possible, and how?
Apparently, Ember has evolved now and there is an ability to pass a parameter to an action:
{{action "functionName" parameter}}
In your case, that would be:
<a {{bindAttr href="url"}}
{{action "appClicked" name on='click'}}>
{{name}}
</a>
However, you could pass any attribute from the model (like the id) instead of the name.
See http://emberjs.com/guides/templates/actions/ for more information.
The API says you can pass in multiple parameters.
html and handlebars:
{{officename}}
<button {{action "actionTest" "hello" "goodbye" officename}}>See parameters through action in the console</button>
controller:
actionTest: function(a, b, c){
console.log(a);
console.log(b);
console.log(c);
},
See it in action in this jsbin
I was thinking something more along the lines of this since you'll have access to a bunch more through an actual view. But Zack, if you could explain a bit more what exactly you're trying to do if this isn't what you're looking for?
App = Ember.Application.create();
App.peopleController = Ember.ArrayController.create({
content: [ { name: 'Roy', url: '#' },
{ name: 'Mike', url: '#' },
{ name: 'Lucy', url: '#' } ]
});
App.PersonView = Ember.View.extend({
tagName: 'li',
content: null,
linkClicked: function() {
console.log(this.getPath('content.name'));
}
});
<ul>
{{#each App.peopleController}}
{{#view App.PersonView contentBinding="this"}}
<a {{bindAttr href="content.url"}} {{action "linkClicked" on="click"}}>
{{content.name}}
</a>
{{/view}}
{{/each}}
</ul>
From subviews, you can attach data-attributes and access them in your controller.
For example, in your view, if you have:
{{#view Ember.Button target="App.controller" action="publish" data-publish=false}}Unpublish{{/view}}
Then in your controller,
App.controller = Ember.Object.extend({
publish: function(v){
var status = v['data-publish'];//your additional information is appended to the view.
}
}
An improvement to Veeb's answer, remember you have the jQuery event so you can do:
// template
<ul>
{{#each applications}}
<li>
<a {{bindAttr href="url"}} param="abc" {{action "appClicked" on="click"}}>
{{name}}
</a>
</li>
{{/each}}
</ul>
// In your js code
appClicked: function (event) {
var param = $(event.target).attr('param');
...
}
You can try to make the parameter an attribute of the <li> or <a> tag and then use jQuery to access it.
Maybe something like
// template
<ul>
{{#each applications}}
<li>
<a {{bindAttr href="url"} param="abc"}
{{action "appClicked" on="click"}}>
{{name}}
</a>
</li>
{{/each}}
</ul>
// In your js code
appClicked: function (event) {
// You may have to play around and check which DOM element
// has the the param attribute. From memory it is the parent.
var param = this.$().parent().attr('param');
...
}

Categories

Resources