ember-helpers
A collection of helpers for Ember.js enabling advanced templating logic.
Usage
Installation
ember install @abcum/ember-helpers
Static helpers
Helper | HTMLBars | Result |
---|---|---|
define | {{define this 'items' (reverse users)}} |
this.set('items', ...) |
run | {{run (transition-to 'route') post}} |
Runs an action with ability to uncurry arguments |
Action helpers
The action helpers enable a variety of advanced actions.
Helper | HTMLBars | Result |
---|---|---|
alert | {{alert "Well hello" "there")}} |
window.alert("Well hello there") |
call | {{some-component clicked=(call "log")}} |
Calls method on route, and bubbles up |
chain | {{chain (action 'one') (action 'two')}} |
one(args).then(two) |
check | {{check (action 'delete')}} |
if (val) delete(); |
confirm | {{confirm "Are you sure?")}} |
window.confirm("Are you sure?") |
console | {{console 'event-name' type='log'}} |
console.log('event-name', ...) |
debounce | {{debounce (action 'increment') 500}} |
Ember.run.debounce(...) |
invoke | {{#link-to 'index' invoke=(action 'save')}} |
Changes route and invokes action |
modify | {{modify model item}} |
model.set('selected', item) |
notify | {{notify "Title" "Body text"}} |
new Notification(...) |
prompt | {{prompt "What is your name?")}} |
window.prompt("What is your name?") |
queue | {{queue (action 'one') (action 'two')}} |
one(args).then(() => two(args)) |
toggle | {{toggle this 'active'}} |
this.toggleProperty('active') |
throttle | {{throttle (action 'increment') 500}} |
Ember.run.throttle(...) |
uncurry | {{uncurry (transition-to 'route') post}} |
Uncurries extra paramaters passed to the action |
Scroll helpers
The scroll helpers enable advanced document and block scroll positioning.
Helper | HTMLBars | Result |
---|---|---|
remember-scroll | {{remember-scroll key='home'}} |
Stores and sets the document body scroll position |
scroll-block | {{scroll-block key='posts'}} |
Creates a div which remembers it's scroll position |
scroll-to | {{scroll-to position=1400}} |
Scrolls to the specified position after an action |
Sorter helpers
The sorter helpers enable advanced sorting logic to extend the sort-by
helper.
Helper | HTMLBars | Result |
---|---|---|
natural-sort | {{sort-by (natural-sort 'name') users}} |
Uses current locale for natural sorting |
Event helpers
The event helpers enable manipulation of browser events.
Helper | HTMLBars | Result |
---|---|---|
drag-get | {{drag-get 'text'}} |
event.dataTransfer.getData('text') |
drag-set | {{drag-set 'text' data}} |
event.dataTransfer.setData('text', data) |
drop-effect | {{drop-effect 'move'}} |
event.dataTransfer.dropEffect = 'move' |
effect-allowed | {{effect-allowed 'move'}} |
event.dataTransfer.effectAllowed = 'move' |
prevent-default | {{prevent-default}} |
event.preventDefault() |
stop-propagation | {{stop-propagation}} |
event.stopPropagation() |
Router helpers
The router helpers enable a selection of router methods.
Helper | HTMLBars | Result |
---|---|---|
is-active | {{if (is-active 'post')}} |
if (this.get('router').isActive('post')) |
history-back | {{history-back}} |
window.history.back() |
history-forward | {{history-forward}} |
window.history.forward() |
open | {{open "https://abcum.com"}} |
window.location.open(...) |
reload | {{reload}} |
window.location.reload(...) |
transition-to | {{transition-to 'post' post.id}} |
this.transitionTo('post', post.id) |
Object helpers
The array helpers enable advanced array logic and manipulation.
Helper | HTMLBars | Result |
---|---|---|
group-by | {{group-by "category" products}} |
products grouped by unique category
|
invoke | {{invoke "save" user}} |
save action called on user model |
match-by | {{match-by "name" "email" search person}} |
true if name , or email contains search
|
object-key | {{object-key "name" person}} |
name property of person object |
Array helpers
The array helpers enable advanced array logic and manipulation.
Helper | HTMLBars | Result |
---|---|---|
any-by | {{#if (any-by "isAdult" users)}} |
if isAdult is truthy on any one of users
|
append | {{#each (append users user)}} |
users array with user appended |
array | {{#each (array 1 2 3 4 5)}} |
[1, 2, 3, 4, 5] |
compact | {{#each (compact users)}} |
users with null or undefined items removed |
contains | {{#if (contains user users)}} |
if users contains user
|
empty | {{#if (empty users)}} |
if users is an empty array |
every-by | {{#if (every-by "isAdult" users)}} |
if isAdult is truthy on every one of users
|
filter | {{#each (filter (action 'check') users)}} |
users where check action is truthy |
filter-by | {{#each (filter-by "isAdult" users)}} |
users where isAdult is truthy |
find | {{#each (find (action 'check') users)}} |
first of users where check action is truthy |
find-by | {{#each (find-by "isAdult" users)}} |
first of users where isAdult is truthy |
first | {{first users)}} |
first item of users
|
flatten | {{#each (flatten multiarray)}} |
flattened array of multiarray
|
includes | {{#if (includes user users)}} |
if users includes user
|
intersect | {{#each (intersect admins users)}} |
intersection of admins and users
|
invoke | {{invoke "save" users}} |
save action called on each model in users
|
join | {{#each (join ", " tags)}} |
Concatenates tags with the separator ,
|
last | {{last users)}} |
last item of users
|
map | {{#each (map (action 'getName') users)}} |
users mapped to the getName callback |
map-by | {{#each (map-by "name" users)}} |
users mapped to the name property |
object-at | {{object-at i users}} |
item at position i in users
|
objects-at | {{objects-at i j ... users}} |
items at position i j ... in users
|
omit | {{#each (omit 3 users)}} |
users with first 3 models omitted |
prepend | {{#each (prepend users user)}} |
users array with user prepended |
range | {{#each (range 1 5)}} |
[1, 2, 3, 4, 5] |
reject | {{#each (reject (action 'check') users)}} |
users where check action is falsy |
reject-by | {{#each (reject-by "isAdult" users)}} |
users where isAdult is falsy |
reverse | {{#each (reverse users)}} |
users in reverse order |
slice | {{#each (slice 0 5 users)}} |
items 0 through 4 from users
|
search-by | {{#each (search-by "name" search users)}} |
users where name contains search
|
sort-by | {{#each (sort-by "name:desc" users)}} |
users sorted by name descending |
sort-locale-by | {{#each (sort-locale-by "age" users)}} |
users locale sorted by age descending |
split | {{#each (split "/" "app/css/app.less")}} |
["app", "css", "app.less"] |
take | {{#each (take 3 users)}} |
first 3 models from users
|
union | {{#each (union admins users)}} |
union of admins and users
|
uniq | {{#each (uniq users)}} |
unique items from users
|
uniq-by | {{#each (uniq-by "email" users)}} |
unique items by email in users
|
w | {{#each (w "One Two Three" "Four")}} |
["One", "Two", "Three", "Four"] |
without | {{#each (without user users)}} |
users array with user removed |
Promise helpers
The promise helpers enable working with models and promises.
Helper | HTMLBars | Result |
---|---|---|
await | {{#if (await promise)}} |
Waits for a promise to resolve |
is-fulfilled | {{#if (is-fulfilled promise)}} |
Returns true when a promise is fulfilled |
is-loaded | {{#if (is-loaded model)}} |
Returns true if the model is currently loaded |
is-pending | {{#if (is-pending promise)}} |
Returns true if a promise is pending |
is-rejected | {{#if (is-rejected promise)}} |
Returns true when a promise is rejected |
is-updating | {{#if (is-updating model)}} |
Returns true if the model is currently updating |
rsvp-all | {{#if (await (rsvp-all tags places))}} |
Promise which waits for all promises to resolve |
rsvp-hash | {{#if (await (rsvp-hash tags=tags))}} |
Promise which waits for all promises to resolve |
rsvp-race | {{#if (await (rsvp-race tags places))}} |
Promise which resolves with the fastest promise |
Format helpers
The format helpers enable easy formatting of different units.
Helper | HTMLBars | Result |
---|---|---|
bytes | {{bytes 134186)}} |
1.34MB |
country | {{country "GBR"}} |
United Kingdom |
convert | {{convert 1 from="GBP" to="EUR"}} |
1.1861095104682045 |
currency | {{currency "GBP"}} |
£ |
duration | {{duration 1283719281 exact=false}} |
1.283719281s |
{{email "info@abcum.com"}} |
mailto:info@abcum.com | |
linkify | {{linkify "Click https://abcum.com"}} |
Click https://abcum.com |
md5 | {{md5 "info@abcum.com"}} |
2a14a47beb82beba88c705145d572702 |
money | {{money 10000 currency="GBP"}} |
£10,000 |
number | {{number 134153 minimumFractionDigits=2}} |
13,415,53.00 |
percent | {{percent 0.3 minimumFractionDigits=2}} |
30.00% |
regexp | {{regexp "[a-zA-Z]*" "ig"}} |
new RegExp('[a-zA-Z]*', 'ig') |
uuid | {{uuid}} |
2690242b-a1f9-47a0-9347-4ed8bc7f09a8 |
Input helpers
The input helpers enable complex regular expressions for easy input box validity checking.
Helper | HTMLBars | Result |
---|---|---|
input-stars | {{input-stars min=1 max=5 value=3}} |
A star rating input field |
pattern-alphanum | {{input pattern=(pattern-alphanum)}} |
Allows a-zA-Z0-9-+ values |
pattern-country | {{input pattern=(pattern-country)}} |
Allows ISO 3166 country codes |
pattern-currency | {{input pattern=(pattern-currency)}} |
Allows ISO 4217 currency codes |
pattern-decimal | {{input pattern=(pattern-decimal)}} |
Allows positive or negative decimals |
pattern-email | {{input pattern=(pattern-email)}} |
Allows email addresses |
pattern-facebook | {{input pattern=(pattern-facebook)}} |
Allows facebook usernames |
pattern-integer | {{input pattern=(pattern-integer)}} |
Allows positive or negative integers |
pattern-letters | {{input pattern=(pattern-letters)}} |
Allows only letter characters |
pattern-numbers | {{input pattern=(pattern-numbers)}} |
Allows only numeric values |
pattern-phone | {{input pattern=(pattern-phone)}} |
Allows phone numbers |
pattern-twitter | {{input pattern=(pattern-twitter)}} |
Allows twitter handles |
pattern-url | {{input pattern=(pattern-url)}} |
Allows urls |
Text helpers
The text helpers enable easy formatting of strings and text.
Helper | HTMLBars | Result |
---|---|---|
camelize | {{camelize "this Is some TEXT"}} |
thisIsSomeTEXT |
capitalize | {{capitalize "this Is some TEXT"}} |
This Is some TEXT |
classify | {{classify "this Is some TEXT"}} |
ThisIsSomeTEXT |
dasherize | {{dasherize "this Is some TEXT"}} |
this-is-some-text |
lcwords | {{lcwords "this Is some TEXT"}} |
this is some tEXT |
lowercase | {{lowercase "this Is some TEXT"}} |
this is some text |
nl2br | {{lowercase "this Is \n some TEXT"}} |
this Is <br> some TEXT |
replace | {{replace "this Is some TEXT" "Is" "Was"}} |
this Was some TEXT |
slug | {{slug "this Is some 'TEXT'"}} |
this-is-some-text |
sanitize | {{sanitize "this Is some TEXT"}} |
Ember.String.htmlSafe('...') |
swapcase | {{swapcase "this Is some TEXT"}} |
THIS iS SOME text |
titleize | {{titleize "this Is some TEXT"}} |
This Is Some Text |
truncate | {{truncate "this Is some TEXT" 10}} |
this Is so... |
ucwords | {{ucwords "this Is some TEXT"}} |
This Is Some TEXT |
underscore | {{underscore "this Is some TEXT"}} |
this_is_some_text |
uppercase | {{uppercase "this Is some TEXT"}} |
THIS IS SOME TEXT |
Logic helpers
The logic helpers enable logic operations in handlebars statements.
Helper | HTMLBars | JavaScript equivalent |
---|---|---|
and | {{if (and a b ...)}} |
if (a && b && ...) |
begs-with | {{if (begs-with a b)}} |
if (a.indexOf(b) === 0) |
ends-with | {{if (ends-with a b)}} |
if (a.indexOf(b, a.length - b.length) !== -1) |
eq | {{if (eq a b)}} |
if (a == b) |
gt | {{if (gt a b)}} |
if (a > b) |
gte | {{if (gte a b)}} |
if (a >= b) |
inside | {{if (inside a b)}} |
if (a.indexOf(b) > -1) |
is | {{if (is a ...)}} |
if (a === true ...) |
isnt | {{if (isnt a ...)}} |
if (a !== true ...) |
ix | {{if (ix a ...)}} |
if (a !== true ...) |
lt | {{if (lt a b)}} |
if (a < b) |
lte | {{if (lte a b)}} |
if (a <= b) |
ne | {{if (ne a b))}} |
if (a !== b) |
not | {{if (not a b))}} |
if (!a && !b && ...) |
or | {{if (or a b ...)}} |
`if (a |
present | {{if (present a ...)}} |
if (Ember.isPresent(a) ...) |
xor | {{if (xor a b)}} |
`if (a && !b |
Math helpers
The math helpers enable maths calculations in handlebars statements.
Helper | HTMLBars | JavaScript equivalent |
---|---|---|
add | {{add a b ...}} |
a + b + ... |
ceil | {{ceil a}} |
Math.ceil(a) |
dec | {{dec a}} |
a - b ? b : 1 |
div | {{div a b ...}} |
a / b / ... |
floor | {{floor a}} |
Math.floor(a) |
inc | {{inc a}} |
a + b ? b : 1 |
max | {{max a b c ...}} |
Math.max([a, b, c, ...]) |
min | {{min a b c ...}} |
Math.min([a, b, c, ...]) |
mod | {{mod a b ...}} |
a % b % ... |
mult | {{mult a b ...}} |
a * b * ... |
random | {{random a b}} |
Math.random(a, b) |
round | {{round a}} |
Math.round(a) |
sqrt | {{sqrt a}} |
Math.sqrt(a) |
sub | {{sub a b ...}} |
a - b - ... |
Examples
Callback helpers
define
Defines the given property on the given object.
run
Allows an action to be called with specified arguments.
Or you can specify that any additional curried arguments will be ignored.
Action helpers
alert
Displays a window.alert
message as a result of an action on a component.
call
Allows a method on the route to be called from a component.
chain
Enables chaining of a sequence of actions together to form a larger action, passing the result of each action to the next action.
If any action in the chain returns a promise, then the chain will wait for the promise to return, and the return value will be piped into the next action. If the Promise rejects, the rest of the chain will be aborted.
check
Checks if a value (as a result of an action) is truthy before running the defined action.
Useful when chaining actions together to prevent an action from running if the previous action returned false.
confirm
Displays a window.confirm
message as a result of an action on a component.
console
Enables logging any passed or curried paramaters to the console
, as a result of an action on a component.
Or you can specify which console
logging type should be used to display the message. The different possible types are trace
, debug
, info
, log
, warn
, error
.
debounce
Ensures an action is triggered only once during the specified time.
link-invoke
Allows an action to be called while transitioning to another route with link-to
.
Or you can use a closure action instead of a action name.
Or you can add action parameters to be passed to the invoked action.
modify
Modifies the current selection of the given array with the curried item object.
export default Ember.Component.extend({
click() {
this.sendAction('onselect', item);
}
});
Or toggle a selected item by passing the selected object and a toggle
option.
export default Ember.Component.extend({
click() {
this.sendAction('onselect', item, { toggle:true, retain: true });
}
});
Or select a range of items by passing the selected object and a range
option.
export default Ember.Component.extend({
click() {
this.sendAction('onselect', item, { range:true, retain: true });
}
});
Or to use a specific key on the controller within which the selection will be stored.
notify
Displays a notification as a result of an action on a component.
prompt
Displays a window.prompt
message as a result of an action on a component.
queue
Enables queuing of a sequence of actions together to form a larger action, passing the original arguments to each action.
If any action in the queue returns a promise, then the queue will wait for the promise to return, before moving onto the next action. If the Promise rejects, the rest of the queue will be aborted.
toggle
Toggles the primary argument as a boolean value.
Or you can toggle between specific values the primary argument as a boolean value.
throttle
Waits for the specified time before running an action, discarding all events in the meantime.
uncurry
Allows an action to be called with specified arguments, whilst ignoring any curried arguments.
Scroll helpers
remember-scroll
Stores and sets the page scroll position of the page.
Or remember the scroll position of individual pages with named keys.
scroll-block
Specify a scrollable area, and remember the scroll position across routes with named keys.
scroll-to
Scroll to a specified position from the top of the page.
Or scroll to a specific element on the page.
Or animate the scrolling by specifying the number of milliseconds.
Sorter helpers
natural-sort
Sorts the given array using a natural sort order with the current locale.
You can also pass asc
or desc
suffixes to specify sort ordering.
Or you can specify that numeric collation should be used when sorting.
Or you can specify that punctuation should be ignored when sorting.
Or you can specify which case should sort first.
Possible values are lower
, upper
, or false
(default).
Or you can specify the sensitivity of the locale sort algorithm.
Possible values are case
, accent
, variant
, or base
(default).
Action helpers
drag-get
Gets metadata from the browser event dataTransfer object.
Or you can use the application/json
mime-type to get the data as an object.
Or use the chain
helper to chain multiple actions together to complete the drag-and-drop functionality.
drag-set
Set custom metadata on the browser event dataTransfer object.
Or you can use the application/json
mime-type to set the data as an object.
Or use the chain
helper to chain multiple actions together to complete the drag-and-drop functionality.
drop-effect
Specifies the dropEffect
property on the event dataTransfer object.
effect-allowed
Specifies the effectAllowed
property on the event dataTransfer object.
prevent-default
Runs the preventDefault
method on the event handler object.
stop-propagation
Runs the stopPropagation
method on the event handler object.
Router helpers
is-active
Detects whether a specific route is active or not.
history-back
Calls window.history.back()
to reverse one position in the browser history.
history-forward
Calls window.history.forward()
to advance one position in the browser history.
open
Calls window.open()
enabling opening a new browser tab or window from an action on a component.
reload
Calls window.location.reload()
enabling reloading the page, or changing the url from an action on a component.
transition-to
Allows the route to be changed from an action on a component, similar to link-to
.
Object helpers
group-by
Groups items in a given array by the given path.
match-by
Returns true if the given properties contain the given value.
You can also use an array containing the properties to search.
object-key
Extracts the property from the given object.
Array helpers
any-by
Checks whether the given property is true
on any item in a given array.
Or if given property is equal to the given value on any item in a given array.
append
Appends each given array to the previous given arrays, resulting in a single flat array.
array
Lets you create arrays directly in the template.
compact
Removes empty values from the given array.
empty
Checks to see if an array is empty.
every-by
Checks whether the given property is true
on every item in a given array.
Or if given property is equal to the given value on every item in a given array.
filter
Returns the given array filtered by a callback.
filter-by
Returns the given array filtered by a property.
Returns the given array filtered by a property.
You can also pass an action as second argument.
find
Returns the first entry matching the given callback from the given array.
find-by
Returns the first entry matching the given value from the given array.
Returns the first entry matching the given value from the given array.
You can also pass an action as second argument.
first
Returns the first object of the given array.
flatten
Returns a flattened array from the given array.
let array = [ [1], [2], [3] ];
includes
Checks to see if an array includes an object.
Or if an array includes an array of objects.
invoke
Calls a method on an object.
Or on each item in an array.
intersect
Returns an array of unique items which are present in all given arrays.
join
Concatenates the given array with an optional separator.
You can use an optional separator.
last
Returns the last object of the given array.
map
Returns the given array mapped to the given callback.
map-by
Returns the given array mapped to the given property.
object-at
Returns the object at the given index
of an array.
objects-at
Returns the object at the given indexes
of an array.
omit
Returns the given array with the first count
items omitted.
prepend
Prepends each given array to the previous given arrays, resulting in a single flat array.
range
Creates an array whose contents is a range of numbers between min and max.
reject
Returns the given array filtered by a callback.
reject-by
Returns the given array omitting those matching the property.
Returns the given array omitting those matching the property.
You can also pass an action as second argument.
reverse
Rearranges the array in reverse order.
slice
Returns a slice of the given array.
search-by
Returns the given array where the given properties contain the given value.
You can also use an array containing the properties to search.
sort-by
Returns the given array sorted by the defined properties.
You can also pass an action as second argument.
sort-locale-by
Returns the given array sorted by the defined properties.
You can also pass asc
or desc
suffixes to specify sort ordering.
Or you can specify that numeric collation should be used when sorting.
Or you can specify that punctuation should be ignored when sorting.
Or you can specify which case should sort first.
Possible values are lower
, upper
, or false
(default).
Or you can specify the sensitivity of the locale sort algorithm.
Possible values are case
, accent
, variant
, or base
(default).
split
Splits a string/strings on a character and returns an array.
take
Returns the given array with the first count
items only.
union
Returns an array of unique items from all of the given arrays.
uniq
Returns an array of unique items from all of the given arrays.
uniq-by
Returns an array of unique items, compared using the given property, from the given array.
w
Splits a string/strings on whitespace or turns multiple words into an array.
without
Returns the given array without the given item or items.
Promise helpers
await
Waits for a promise to resolve, and passes the promise contents to the helper.
If the author
exists, but the promise has not yet been loaded, then the template will render anyway.
is-fulfilled
Returns true when a promise is fulfilled.
is-loaded
Returns true if the ember-data
model is currently loading.
is-pending
Returns true if a promise is pending.
is-rejected
Returns true when a promise is rejected.
is-updating
Returns true if the ember-data
model is currently updating.
rsvp-all
Returns a new promise which is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The returned value is an array of fulfillment values for the passed in promises.
rsvp-hash
Returns a new promise which is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The returned promise is fulfilled with a hash that has the same key names as the promises object argument.
rsvp-race
Returns a new promise which is fulfilled when the first promise to be fulfilled is resolved. The returned value is the value of the first fulfilled promise.
Development
-
make install
(install bower and ember-cli dependencies) -
make upgrade
(upgrade ember-cli to the specified version) -
make tests
(run all tests defined in the package)