Created
November 17, 2017 16:54
-
-
Save ryanlabouve/ee04c091ed81a0ae1049a94ec0603006 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is the toggle helper from Ember composable helper, | |
// but I'm adding some annotations | |
// Ref: https://github.com/DockYard/ember-composable-helpers/blob/master/addon/helpers/toggle.js | |
import { helper } from '@ember/component/helper'; | |
import { get } from '@ember/object'; | |
import { set } from '@ember/object'; | |
import { isPresent } from '@ember/utils'; | |
// FP - First Pass | |
// SP - Second Pass | |
// [FP] Looks like this gives us a way to either get the next index | |
// Or throw a falsey value of 0 | |
function nextIndex(length, currentIdx) { | |
if (currentIdx === -1 || currentIdx + 1 === length) { | |
return 0; | |
} | |
return currentIdx + 1; | |
} | |
// Keep in mind, here is the API | |
// <button {{action (toggle "isExpanded" this)}}> | |
export function toggle([prop, obj, ...values]) { | |
return function() { | |
// This would be like `get(this, 'nightMode')` in our case | |
let currentValue = get(obj, prop); | |
// Going to completely ignore this for now since we are not passing in more values | |
if (isPresent(values)) { | |
let currentIdx = values.indexOf(currentValue); | |
let nextIdx = nextIndex(get(values, 'length'), currentIdx); | |
return set(obj, prop, values[nextIdx]); | |
} | |
// This is just doing `set(this, 'nightMode', !currentValue)` | |
return set(obj, prop, !currentValue); | |
}; | |
} | |
export default helper(toggle); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment