Created
May 11, 2019 21:30
-
-
Save eccegordo/ec63240eb2e7c46c7405e9f7d98cc42f to your computer and use it in GitHub Desktop.
Redux like store as ember data model instance
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
/* | |
my-redux-store-instance | |
A model to give us some redux store like behavior | |
Note that typically the state object comes from a reducer | |
The responsibility of this model is to give us something we can | |
store our state history when using the redux pattern | |
Also this model contains some helper functions to build stuff like redux actions | |
*/ | |
import Ember from 'ember'; | |
import DS from 'ember-data'; | |
const { get, set, computed, isEmpty, isPresent, A } = Ember; | |
export default DS.Model.extend({ | |
name: DS.attr('string'), // a friendly name of the store | |
context: DS.attr('string'), // typically the name of the component or controller that this was used in | |
reducerName: DS.attr('string'), // name the reducer that we use to derive state | |
state: DS.attr(), | |
maxHistorySize: DS.attr('number', { defaultValue: 10 }), | |
recentStateHistory: DS.attr({ defaultValue: function(){ return A([]);} }), | |
}).extend({ | |
history: computed('recentStateHistory.length', 'recentStateHistory.[]', 'recentStateHistory', function(){ | |
let recentStateHistory = get(this, 'recentStateHistory'); | |
return recentStateHistory; | |
}), | |
addToStateHistory(state){ | |
let maxHistorySize = get(this, 'maxHistorySize'); | |
let recentStateHistory = get(this, 'recentStateHistory'); | |
// behave like a circular buffer | |
if (recentStateHistory.length === maxHistorySize){ | |
recentStateHistory.pop(); | |
} | |
recentStateHistory.unshift(state); | |
let updatedHistory = A(recentStateHistory); | |
set(this, 'recentStateHistory', updatedHistory.toArray()); | |
set(this, 'state', state); | |
}, | |
/** | |
build a redux like action | |
{ | |
type: 'ACTION_FOR_THING', | |
payload: { | |
name: 'My Thing' | |
selected: true | |
} | |
} | |
*/ | |
buildAction(type='NOOP', payload=null){ | |
let action = { | |
type: type | |
}; | |
if (isEmpty(type)){ | |
console.error('tried to create action without type'); | |
return null; | |
} | |
if (isPresent(payload)){ | |
action.payload = payload; | |
} | |
return action; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment