Last active
August 6, 2017 06:56
-
-
Save mwpastore/561d565c40bdfac6a7828c12600e52a5 to your computer and use it in GitHub Desktop.
cached computed macro
This file contains 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
import { run } from '@ember/runloop'; | |
import { computed } from '@ember/object'; | |
const { stringify } = JSON; | |
export default function(...props) { | |
const { getState, update } = props.pop(); | |
const strippedProps = props.map((prop) => { | |
let index = prop.indexOf('.[]'); | |
if (index === -1) { | |
index = prop.indexOf('.@each'); | |
} | |
if (index === -1) { | |
return prop; | |
} | |
return prop.slice(0, index); | |
}); | |
function stateHelper() { | |
const | |
entries = this.getProperties(strippedProps), | |
values = Object.values(entries), | |
state = getState.apply(this, values); | |
return { | |
values, | |
state: (typeof state === 'string') ? state : stringify(state) | |
}; | |
} | |
let cachedState; | |
return computed(...props, function() { | |
const { state, values } = stateHelper.call(this); | |
if (state === cachedState) { | |
return; | |
} | |
run.scheduleOnce('afterRender', null, () => { | |
update.apply(this, values); | |
const { state } = stateHelper.call(this); | |
cachedState = state; | |
}); | |
}).readOnly(); | |
} |
This file contains 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
import Controller from '@ember/controller'; | |
import { run } from '@ember/runloop'; | |
import { inject as injectService } from '@ember/service'; | |
import cachedComputed from '../macros/cached-computed'; | |
export default Controller.extend({ | |
cart: injectService(), | |
_projectContactManager: cachedComputed('cart.order.project.contacts.@each.isBlank', { | |
getState: contacts => contacts.mapBy('isBlank'), | |
update(contacts) { | |
const blankContacts = contacts.filterBy('isBlank'); | |
blankContacts.forEach((blankContact) => { | |
// remove any blank contacts from the list | |
contacts.removeObject(blankContact); | |
// garbage-collect orphaned contacts | |
run.later(blankContact, 'rollbackAttributes'); | |
}); | |
// create a new blank contact at the end of the list | |
contacts.createRecord({ isOwned: true }); | |
} | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment