Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stefanpenner/8ee8962b5ea0795ff259 to your computer and use it in GitHub Desktop.
Save stefanpenner/8ee8962b5ea0795ff259 to your computer and use it in GitHub Desktop.
#12842
import Ember from 'ember';
export default Ember.Controller.extend({
elements: [
{name: "Uranium"},
{name: "Plutonium"},
{name: "Francium"},
{name: "Einstanium"}
],
searchQuery: ''
});
<h1>Demonstration</h1>
Search for elements by name: {{input type="text" value=searchQuery}}
<p style="color: blue;">
There are {{numberOfFilteredElements}} elements matching your search:
</p>
<!-- We clearly express that changing "numberOfFilteredElements" in the componnent should change "numberOfFilteredElements" in the controller too -->
{{my-list model=elements searchQuery=searchQuery numberOfFilteredElements=(mut numberOfFilteredElements)}}
<hr>
<h1>Notes</h1>
<p>The rectangle is the component.</p>
<p>The sentence in blue should be "There are N elements matching your search" with N being the number of elements matching the search.</p>
<p>If you search things, "numberOfFilteredElements" should get updated in the component, and thus updated here too. You can clearly see it is not. <br>
But if you change "numberOfFilteredElements" in the component using the number imput (in red) in the component, it is effectively synchronized. Why?</p>
import Ember from 'ember';
export default Ember.Component.extend({
// Just some basic styling to distinguish what belongs to the component
attributeBindings: ['style'],
style: 'border: 1px solid black;',
init() {
this._super(...arguments);
window.foo = this;
},
searchQuery: '', // The search input
model: [], // All the elements to search in
// Return the elements that match the search query
filteredElements: Ember.computed('model.[]', 'searchQuery', function () {
let searchQuery = this.get('searchQuery').toLowerCase();
let elements = this.get('model');
return elements.filter(e => {
let name = e.name.toLowerCase();
return name.indexOf(searchQuery) > -1;
});
}),
// Return the number of elements that match the search query. This is the property we would like to be able to get from OUTSIDE the component
numberOfFilteredElements: Ember.computed('filteredElements', function () {
return this.get('filteredElements.length');
}).readOnly()
})
<ul>
{{#each filteredElements as |e|}}
<li>{{e.name}}</li>
{{/each}}
</ul>
<p style="color: red;">
Do not use this box before reading the notes:
{{input type="number" value=numberOfFilteredElements}}
</p>
{
"version": "0.5.0",
"EmberENV": {
"FEATURES": {}
},
"options": {
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.2.0",
"ember-data": "2.2.0",
"ember-template-compiler": "2.2.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment