Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* Put your CSS here */
html, body {
margin: 20px;
}
.color {
height: 200px;
width: 200px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Wrapping localStorage in Ember Demo" />
<meta charset="utf-8">
<title>Ember Starter Kit</title>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/2.1.0/normalize.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v1.3.0.js"></script>
<script src="http://builds.emberjs.com/tags/v1.5.0/ember.js"></script>
</head>
<body>
<script type="text/x-handlebars">
<h2>Wrapping localStorage in Ember Demo</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<p>Pick your favorite color, then close this tab an come back:</p>
{{custom-color colors=model}}
<p>Also check <code>localStorage.color</code> in the Console.</p>
</script>
<script type="text/x-handlebars" data-template-name="components/custom-color">
<ul>
{{#each item in colors}}
<li><a {{action setColor item}} href="#">{{item}}</a></li>
{{/each}}
</ul>
{{input name="color" value=color}}
<a href="#" {{action clear}}>clear</a>
</script>
</body>
</html>
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'green'];
}
});
App.LocalStorage = Ember.Object.extend({
unknownProperty: function(key) {
return localStorage[key];
},
setUnknownProperty: function(key, value) {
if(Ember.isNone(value)) {
delete localStorage[key];
} else {
localStorage[key] = value;
}
this.notifyPropertyChange(key);
return value;
},
clear: function() {
this.beginPropertyChanges();
for (var i=0, l=localStorage.length; i<l; i++){
this.set(localStorage.key(i));
}
localStorage.clear();
this.endPropertyChanges();
}
});
App.CustomColorComponent = Ember.Component.extend({
color: Ember.computed.alias('storage.color'),
createLocalStorage: function() {
this.set('storage', App.LocalStorage.create());
}.on('init'),
actions: {
setColor: function(value) {
this.set('color', value);
},
clear: function() {
this.get('storage').clear();
}
},
classNames: ['color'],
attributeBindings: ['style'],
style: function() {
var color = this.get('color');
return "background-color: " + color;
}.property('color')
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment