<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Midnight Musings</title>
	<atom:link href="http://taurenmills.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://taurenmills.wordpress.com</link>
	<description>Javascript, Node.js, Backbone.js, Coffeescript, UX, and more</description>
	<lastBuildDate>Sun, 16 Oct 2011 09:17:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='taurenmills.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Midnight Musings</title>
		<link>http://taurenmills.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://taurenmills.wordpress.com/osd.xml" title="Midnight Musings" />
	<atom:link rel='hub' href='http://taurenmills.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Simplify using static class properties in Backbone.js with Coffeescript</title>
		<link>http://taurenmills.wordpress.com/2011/10/08/backbone-js-with-class-properties/</link>
		<comments>http://taurenmills.wordpress.com/2011/10/08/backbone-js-with-class-properties/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 10:39:40 +0000</pubDate>
		<dc:creator>taurenmills</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[backbone.js]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://taurenmills.wordpress.com/?p=1</guid>
		<description><![CDATA[Do your Backbone models ever need to share common data between them? Then you might want to consider using class properties and class methods. I&#8217;ve been exploring this recently, and thought I&#8217;d share my findings. The source included in this post can be found in my sample-backbone-static github repository. There is also an example of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=taurenmills.wordpress.com&amp;blog=28237347&amp;post=1&amp;subd=taurenmills&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Do your <a href="http://documentcloud.github.com/backbone">Backbone</a> models ever need to share common data between them? Then you might want to consider using class properties and class methods. I&#8217;ve been exploring this recently, and thought I&#8217;d share my findings. The source included in this post can be found in my <a href="https://github.com/tauren/sample-backbone-static">sample-backbone-static</a> github repository. There is also an <a href="https://github.com/tauren/sample-backbone-static/blob/master/factory.js">example of the Factory pattern</a>, courtesy of Johnny Oshika, that isn&#8217;t described in this post.</p>
<p>First, I&#8217;ll start with a basic example in <em>javascript</em> that shows how to define a backbone model with class properties.</p>
<p><pre class="brush: jscript;">
var Sample = Backbone.Model.extend({
  initialize: function() {
  }
},{
  message: &quot;No message has been set&quot;,
  setMessage: function(value) {
    this.message = value;
  }
});
</pre></p>
<p>The first parameter passed to <code>Backbone.Model.extend</code> should contain standard Backbone properties, such as <code>initialize</code>, <code>defaults</code>, <code>validate</code>, etc.</p>
<p>If a second parameter is passed to <code>extend</code>, the properties in it become <strong>class properties</strong> that are attached directly to the constructor function. In other words, the class properties <code>message</code> and <code>setMessage</code> would be accessed using the <code>Sample</code> class, and not from an instance of that class:</p>
<p><pre class="brush: jscript;">
Sample.setMessage(&quot;Hello World&quot;);
console.log(Sample.message);
</pre></p>
<p>These class properties may also be referred to as <strong>static properties</strong> or <strong>static methods</strong>. Keep in mind that these values do not change for any given instance of the <code>Sample</code> class. They are not instance properties, but static class properties.</p>
<p>Also note that the <code>setMessage</code> function uses the <code>this</code> keyword. Normally, <code>this</code> is reserved for use within instances of a class. But when it is used in a static function, it accesses other static properties or functions within that class. It is important to understand this distinction, because a static function can not access an instance&#8217;s properties.</p>
<p>Now, let&#8217;s switch from javascript to <a href="http://jashkenas.github.com/coffee-script">coffeescript</a>. Backbone has excellent coffeescript integration, and working in coffeescript feels much cleaner to me. Below is a more elaborate example in coffeescript. Unfortunately, WordPress doesn&#8217;t support coffeescript highlighting.</p>
<p><pre class="brush: jscript;">
class Animal extends Backbone.Model
  # Distance this animal instance has moved
  distance: 0

  # Move this animal instance
  move: (meters) -&gt;
    # Display message about animal and distance moved
    console.log &quot;#{@get('name')} #{@constructor.motion} #{meters}m.&quot;
    # Record distance move by this animal instance
    @distance += meters
    # console.log @constructor.name
    # Record this distance in static storage
    @constructor.addDistance @, meters

  # Get the distance this animal instance moved
  getDistance: -&gt;
    @distance

  # Static storage object to record total distances moved
  # by each animal type
  @distances: {}

  # Static function to add a distance to an animal type
  @addDistance: (inst, meters) -&gt;
    # Get the type of anmial to add a distance to
    type = inst.constructor.type
    # Exit if running on the base Animal class
    return if not type
    # Retrieve data or initalize this type in storage
    @distances[type] = @distances[type] or 0
    # Add new distance to total animal type distance
    @distances[type] += meters

  # Static function to retrieve the distance moved by an
  # animal type. If called on base Animal, returns total
  # distance for all animals
  @getDistance: -&gt;
    # Return distance moved by just one type of animal
    return @distances[@type] if @type
    # Get an array of distances moved by each animal type
    meters = (val for key, val of @distances)
    # Return the sum of all distances moved by all animals
    _.reduce(meters, ((memo, num) -&gt; memo + num), 0)
</pre></p>
<p>The base <code>Animal</code> class defined above is used to display messages about movements that animals make. It is based on the sample in the <a href="http://jashkenas.github.com/coffee-script/#classes">coffeescript documentation</a>. I&#8217;ve enhanced <code>Animal</code> to also keep track of the total distance a particular (instance) animal moves as well as the total distance that all animals (class) of each animal type has moved. This is accomplished by using both instance and class properties and methods.</p>
<p>The first thing to notice above is that class properties are prefixed with an <code>@</code> symbol, as you can see in the definition of <code>@distances</code>, <code>@addDistance</code>, and <code>@getDistance</code>. In contrast, the <code>move</code> function does not have this prefix, which means it is an instance method, not a static function.</p>
<p>There are several great things about using coffeescript when working with classes, inheritance, and class properties. First is that you can define all of your functions and properties in any order you want, and simply prefix static ones with an <code>@</code> symbol. Secondly, coffeescript provides a nice <code>extends</code> syntax for creating a class hierarchy. Also, inside of a method, you can use the <code>@</code> symbol to represent the <code>this</code> object. In the context of an instance, <code>@</code> refers to the instance itself, but in the context of a class method, it refers to the class constructor.</p>
<p><pre class="brush: jscript;">
class Snake extends Animal
  @type: 'Snake'
  @motion: 'slithers'
  move: (m)-&gt;
    console.log &quot;#{@get('name')} hides under a rock&quot;
    super m

class Horse extends Animal
  @type: 'Horse'
  @motion: 'gallops'
</pre></p>
<p>As you can see, subclass implementations of <code>Animal</code> are very simple. I&#8217;ve defined the <code>@type</code> and <code>@motion</code> as class properties. I&#8217;ve overridden the move function for <code>Snake</code>.</p>
<p>Now let&#8217;s do something with this code:</p>
<p><pre class="brush: jscript;">
sam = new Snake
  name: 'Sammy the Python'
tom = new Horse
  name: 'Tommy the Palomino'
jon = new Horse
  name: 'Jonny the Arabian'
sam.move(5)
tom.move(45)
jon.move(40)
sam.move(10)
console.log &quot;Sammy moved #{sam.getDistance()}m total.&quot;
console.log &quot;Tommy moved #{tom.getDistance()}m total.&quot;
console.log &quot;Jonny moved #{jon.getDistance()}m total.&quot;
console.log &quot;All snakes moved #{Snake.getDistance()}m.&quot;
console.log &quot;All horses moved #{Horse.getDistance()}m.&quot;
console.log &quot;All animals moved #{Animal.getDistance()}m.&quot;
</pre></p>
<p>Which outputs:</p>
<p><pre class="brush: jscript;">
Sammy the Python hides under a rock
Sammy the Python slithers 5m.
Tommy the Palomino gallops 45m.
Jonny the Arabian gallops 40m.
Sammy the Python hides under a rock
Sammy the Python slithers 10m.
Sammy moved 15m total.
Tommy moved 45m total.
Jonny moved 40m total.
All snakes moved 15m.
All horses moved 85m.
All animals moved 100m.
</pre></p>
<p>Here&#8217;s what&#8217;s going on when an animal moves:</p>
<ul>
<li>If the subclass has <code>move</code> defined, as in <code>Snake</code>, then it overrides the <code>move</code> function in <code>Animal</code>. If the subclass does not define <code>move</code>, as in <code>Horse</code>, then the <code>move</code> function in <code>Animal</code> is executed.</li>
<li>If a method in a subclass calls super, the corresponding method in the base class will be executed, as can be seen in <code>Snake</code>. Note that <code>super</code> is another nice feature of coffeescript which would correspond to the following javascript in <code>Snake</code>: <code>Animal.prototype.move.call(this, m)</code>. It is not required to call <code>super</code>, only do so if you want the code in the base class to be executed as well as the code in your subclass.</li>
<li><code>Animal.move</code> prints a message with the animal&#8217;s name, motion, and distance. The key thing to notice here is that the name is retrieved from the model instance, but the motion is pulled from the static class properties using the syntax <code>@constructor.motion</code>.</li>
<li>The distance moved by a specific animal is recorded as an instance property called <code>distance</code>.</li>
<li>The static method <code>addDistance</code> is called, passing it the animal instance, and the distance.</li>
<li>It then determines the type of animal with <code>inst.constructor.type</code>. We exit if the type doesn&#8217;t exist, preventing <code>Animal.addDistance</code> from being run, as it can only be run on a subclass.</li>
<li>Lastly, we make sure the static property <code>@distances</code> has a value defined for this type of animal, and we add the new distance to it.</li>
</ul>
<p>And when we retrieve the distance moved using <code>getDistance</code>:</p>
<ul>
<li>If <code>getDistance</code> is called on an instance, such as <code>sam.getDistance()</code>, then the distance moved by Sammy is returned. This is because the instance method <code>getDistance</code> is called, not the static method <code>@getDistance</code>.</li>
<li>If <code>@getDistance</code> is called on a subclass, such as <code>Snake.getDistance()</code>, then the distance moved by all Snakes is returned.</li>
<li>Otherwise, if <code>Animal.getDistance()</code> is called, then the distances of all animals is added up and returned.</li>
</ul>
<p>I&#8217;d like to improve this so that I don&#8217;t need to define @type on all subclasses. In many browsers, it is possible to get the name of the class using @constructor.name, which would do the trick. But of course, this <a href="http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript/332429#332429">does not work in IE</a>. I found defining @type to be simple and effective, but I&#8217;m open to other suggestions.</p>
<p>This just touches the surface of using class properties and methods. I&#8217;m sure I&#8217;ll be using this in my projects. Please share your thoughts in the comments!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/taurenmills.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/taurenmills.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/taurenmills.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/taurenmills.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/taurenmills.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/taurenmills.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/taurenmills.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/taurenmills.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/taurenmills.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/taurenmills.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/taurenmills.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/taurenmills.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/taurenmills.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/taurenmills.wordpress.com/1/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=taurenmills.wordpress.com&amp;blog=28237347&amp;post=1&amp;subd=taurenmills&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://taurenmills.wordpress.com/2011/10/08/backbone-js-with-class-properties/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7c9d7ad07d30a60c44d9bb236dcaefe5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">taurenmills</media:title>
		</media:content>
	</item>
	</channel>
</rss>
