<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chris Atkins on Medium]]></title>
        <description><![CDATA[Stories by Chris Atkins on Medium]]></description>
        <link>https://medium.com/@itscatkins?source=rss-b645121b0865------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WBVuZvZR0wa5a6tC.jpeg</url>
            <title>Stories by Chris Atkins on Medium</title>
            <link>https://medium.com/@itscatkins?source=rss-b645121b0865------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:36:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itscatkins/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Metaprogramming in EmberJS]]></title>
            <link>https://medium.com/the-ember-way/metaprogramming-in-emberjs-627921395299?source=rss-b645121b0865------2</link>
            <guid isPermaLink="false">https://medium.com/p/627921395299</guid>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[ember]]></category>
            <dc:creator><![CDATA[Chris Atkins]]></dc:creator>
            <pubDate>Sun, 16 Nov 2014 06:37:37 GMT</pubDate>
            <atom:updated>2016-06-21T17:44:37.490Z</atom:updated>
            <content:encoded><![CDATA[<h2>Metaprogramming and client side storage with EmberJS</h2><h3>Building an Ember friendly LocalStorage adapter</h3><p>When building web applications we often need to persist little bits of data or configuration that isn’t strictly part of our application’s <em>model</em> layer. When working on Ruby on Rails apps, I tend to reach for the ultra snazzy data structure server <a href="http://redis.io/">Redis</a> for that kind of thing, and so far it’s worked a charm. When working on <em>ambitious</em> front end applications, the kind that <a href="http://emberjs.com/">EmberJS</a> excels at, we also have a need to store transient data, and we have a few different options.</p><p>I’ll start off with a bit of background on browser based storage, and move in to a more concrete example of how we can make Local Storage integrate with EmberJS.</p><p><strong>TLDR; — </strong>Check out a <a href="http://emberjs.jsbin.com/lasexu/2/edit">working example on JSBin.</a></p><h4>Cookies</h4><p>A well supported option is to use cookies. Cookies have a fairly straightforward API, but have a couple of downsides. All data stored in cookies gets sent to your sever with every request, bloating your bandwidth use. Also, we’re limited to about 4KB of storage with cookies.</p><h4>Web Storage</h4><p>Another option is to use the Web Storage API. The HTML5 Web Storage API provides us simple key value storage up to about 5MB, which should be plenty for a our kind of workloads. There are two main flavours of web storage, namely <em>Session Storage </em>and <em>Local Storage</em>, each with the same API.</p><p>Session Storage lets us persist data for the duration of a <em>session.</em></p><blockquote><em>A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated. — </em><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage"><em>Mozilla DOM Storage Guide</em></a></blockquote><h4>Local Storage</h4><p>Local Storage on the other hand lasts indefinitely, between browser restarts and computer reboots, and will stick around until the user clears their browsing data. Let’s take a look to see how it works. Feel free to pop open your Javascript console (Command + Option + J on Chrome for OSX) and try out the examples below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1c28fcc2399b47b6f828dfb3e6a9774/href">https://medium.com/media/b1c28fcc2399b47b6f828dfb3e6a9774/href</a></iframe><p>As we can see, the <em>localStorage </em>object can be used much in the same way as a normal JavaScript object, with a couple of extra methods on board. What if we want to store something a little bit more complex, like an an array, or object?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55752ab438f3790dbea78e02d2c7de53/href">https://medium.com/media/55752ab438f3790dbea78e02d2c7de53/href</a></iframe><p>As we can see, localStorage calls <em>toString() </em>on each value as we save it, so we’ve hit a small hurdle. Luckily, the browser’s built in JSON methods jump in and save the day.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5fc1c1dc5d6d1824ac1660374f2318f/href">https://medium.com/media/a5fc1c1dc5d6d1824ac1660374f2318f/href</a></iframe><p>Now we can save and load anything that JSON supports and all is good in the world.</p><h4>Walking the Ember Way</h4><p>EmberJS gets a lot of it’s strength by <a href="http://emberjs.com/guides/object-model/classes-and-instances/">augmenting JavaScript’s Object Model</a> with some of it’s own abstractions including bindings and computed properties. With a little bit of legwork, we can build a lightweight wrapper for the <em>localStorage </em>object that lets us embrace the <em>Ember Way </em>of doing things, and also makes it a lot easier to mock out in tests.</p><p>First lets take a look at the completed storage wrapper, and I’ll walk through each of it’s parts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec003b6b836c02ffbfdeff432371bd9d/href">https://medium.com/media/ec003b6b836c02ffbfdeff432371bd9d/href</a></iframe><p><em>Note: this example is using the Globals method of bootstrapping an Ember app, but would only take small modifications to work with ES6 modules.</em></p><p>Our wrapper is created by simply extending from <a href="http://emberjs.com/api/classes/Ember.Object.html">Ember.Object</a> and implementing the properties we’d like. This gives us the base we need to let us bind to properties in localStorage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cc20abc50895e3240dae51b42303371/href">https://medium.com/media/0cc20abc50895e3240dae51b42303371/href</a></iframe><p>In this case, we’re defaulting the persistence to use <em>window.localStorage </em>object, but you could as easily switch out the persistence for <em>window.sessionStorage</em>, or any other object that implements the same public API. This is particularly useful for unit testing, where you’d likely want to stub out the actual storage using <a href="http://sinonjs.org/">SinonJS</a> or another mocking framework.</p><p>We’re also providing a namespace for our keys. On the server, I tend to use the <a href="https://github.com/resque/redis-namespace">Redis Namespace</a> gem to keep keys used by my app seperate from ones used by caches etc. whilst using the same Redis database and connection. We can take a similar approach on the client side. Some javascript libraries, particularly analytics scripts, make use of localStorage to get their work done. We don’t want to step on each other’s toes so we’ll be prefixing all of our keys with the namespace provided here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c17a9f2cc4d121d07b7450a1a54274fa/href">https://medium.com/media/c17a9f2cc4d121d07b7450a1a54274fa/href</a></iframe><p>With our storage service being able to store arbitrary information, we’re not going to know all of the properties that can be stored ahead of time. We could implement properties for each key we want to store, but that would get unwieldy very quickly, so we turn to <em>meta-programming </em>for help.</p><blockquote><em>When we call </em><a href="http://emberjs.com/api/classes/Ember.Object.html#method_get"><strong><em>Ember.Object#get</em></strong></a><strong><em> </em></strong><em>with a property name that hasn’t explicitly been implemented, the call is delegated to the </em><strong><em>unknownProperty </em></strong><em>method. When implemented, we can create </em>virtual properties <em>on our object. Ruby developers would be familiar with this sort of behaviour with the </em><a href="http://www.ruby-doc.org/core-2.1.0/BasicObject.html#method-i-method_missing"><strong><em>method_missing</em></strong></a><strong><em> </em></strong><em>method.</em></blockquote><p>In our case, our virtual property delegates the method to the <em>localStorage </em>object. We generate the key with the namespace, fetch the data, deserialize it as JSON, and voilà, we have our data. Having the method implemented as a computed property, we can now bind to the values in templates, and observe them for changes.</p><p>How about setting keys you ask? Well, we do the same thing in reverse.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c97bbe588b5ef5ac94b61cf315482cd3/href">https://medium.com/media/c97bbe588b5ef5ac94b61cf315482cd3/href</a></iframe><p>We namespace the key, serialize the value as JSON and save the JSON string onto localStorage. To make sure that our bindings stay up to date, we have to notify anything binding to the virtual property by calling the <a href="http://emberjs.com/api/classes/Ember.Object.html#method_notifyPropertyChange">notifyPropertyChanged</a> method.</p><blockquote><em>When calling </em><a href="http://emberjs.com/api/classes/Ember.Object.html#method_set"><strong><em>Ember.Object#set</em></strong></a><strong><em> </em></strong><em>with a key that isn’t defined ahead of time, it first calls the </em><strong><em>setUnknownProperty </em></strong><em>method. If that method is implemented and returns </em><strong><em>undefined</em></strong><em>, then the setter will set the property directly on the object. If however, the method returns a non-undefined value, it will do nothing afterwards as the implementation has flagged it as handled.</em></blockquote><h4>Communication between tabs</h4><p>For bonus points, we’ll also implement a handler for the <em>storage </em>event which is fired when storage is updated in other tabs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c7f54e6e3516c7098c0c65b706b6bfa/href">https://medium.com/media/0c7f54e6e3516c7098c0c65b706b6bfa/href</a></iframe><p>When our storage service is created, we set up an event handler to monitor the <em>storage </em>event. We basically check to see if the key modified is in our app’s namespace, and if it is, notify all observers that the property is updated. Now we can have properties in sync between open tabs with minimal fuss.</p><h4>Wiring it all up</h4><p>Now that we’ve implemented the storage service, we need to get it into our application and do something useful with it. For this, we need to make use of an <em>initializer </em>to <em>inject </em>the service into our objects. Read more in the docs for <a href="http://emberjs.com/api/classes/Ember.Application.html#method_initializer">Ember.Application#initalizer</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32a2fc1a2c3d784470647f5659e949cf/href">https://medium.com/media/32a2fc1a2c3d784470647f5659e949cf/href</a></iframe><p>Here we’ve registered our service into the applications <em>container </em>and made it available as the <em>storage </em>property in all of our routes and controllers. And we’re all set up. We can bind to this property in templates, controllers and routes and it will stick around, and stay in sync.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5883f36954a6b6d20ece35312883534b/href">https://medium.com/media/5883f36954a6b6d20ece35312883534b/href</a></iframe><p>Have a look at this complete example on JSBin. Open a few tabs, restart your browser,</p><p><a href="http://emberjs.jsbin.com/lasexu/2/edit?html,js,output">JS Bin</a></p><h4>Thanks for reading!</h4><p>This post ended up being quite long, but if you’ve made it this far, thanks for reading, I hope that this helps you understand a little bit more about meta-programming, and how easy EmberJS makes to get things done.</p><p>If you’ve got any feedback, or I’ve said something silly, feel free to hit me up on twitter at <a href="https://twitter.com/itscatkins">@itscatkins</a>.</p><p>Also quick shoutout to my co-workers at Doceo @sugarpirate_ and <a href="http://ctountzis/">@ctountzis</a> who have been churning out some great articles on EmberJS, and inspired me to start writing again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=627921395299" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-ember-way/metaprogramming-in-emberjs-627921395299">Metaprogramming in EmberJS</a> was originally published in <a href="https://medium.com/the-ember-way">The Ember Way</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>