Skip to content

Instantly share code, notes, and snippets.

@andybluntish
Last active August 26, 2016 06:36
Show Gist options
  • Save andybluntish/412ed496527db0d0279c8c71feae5bdd to your computer and use it in GitHub Desktop.
Save andybluntish/412ed496527db0d0279c8c71feae5bdd to your computer and use it in GitHub Desktop.
Search Box
import Ember from 'ember';
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
items: ['one', 'two', 'green', 'blue'],
selectedItem: null,
actions: {
selectItem(item) {
this.set('selectedItem', item)
}
}
});
import Ember from 'ember';
const {
Component,
K,
computed,
get,
set,
isEmpty
} = Ember;
export default Component.extend({
classNames: ['search-box'],
items: K,
selectItem: K,
searchValue: '',
optionsVisible: false,
filteredOptions: computed('searchValue', 'items', {
get() {
const searchValue = get(this, 'searchValue');
const items = get(this, 'items');
if (isEmpty(searchValue)) {
return items;
} else {
return items.filter((item) => {
return new RegExp(`${searchValue}`, 'i').test(item);
})
}
}
}),
actions: {
focusIn() {
set(this, 'optionsVisible', true);
},
focusOut() {
set(this, 'optionsVisible', false);
},
clickItem(item) {
set(this, 'searchValue', item)
get(this, 'selectItem')(item)
},
// prevents the input from losing focus when item is clicked
// no-op because actions "prevent default" by default
onMouseDown() { }
}
});
<h2 class="search-box__title">Search Box</h2>
{{input
value=searchValue
focus-in=(action "focusIn")
focus-out=(action "focusOut")
class="search-box__input"
}}
{{#if optionsVisible}}
<ul class="search-box__list">
{{#each filteredOptions as |item|}}
<li class="search-box__item" {{action "clickItem" item}} {{action "onMouseDown" on="mouseDown"}}>
{{item}}
</li>
{{/each}}
</ul>
{{/if}}
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin: 12px 16px;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12pt;
color: #444;
}
/* Search Box */
.search-box {
padding: 0.5rem;
box-shadow: 0 1px 5px hsla(0, 0%, 0%, 0.15);
background: white;
}
.search-box__title {
margin: 0 0 0.5rem;
padding-bottom: 0.25rem;
border-bottom: 1px solid #eee;
}
.search-box__input {
display: block;
width: 100%;
margin: 0;
padding: 0.5rem;
font-size: 120%;
}
.search-box__list {
list-style: none;
margin: 0;
padding: 0
}
.search-box__item {
padding: 0.5rem;
}
.search-box__item:nth-child(2n) {
background: #f9f9f9;
}
.search-box__item:hover {
background: #f4f4f4;
}
<p>Selected item: {{selectedItem}}</p>
{{search-box items=items selectItem=(action 'selectItem')}}
{
"version": "0.10.4",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.7.0",
"ember-data": "2.7.0",
"ember-template-compiler": "2.7.0"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment