Monthly Archives: August 2013

Real JavaScript Enums with enum.js

I stayed at home yesterday and had nothing to do, so I tried to implement enums in pure JavaScript. It worked quite well as you can see on my GitHub profile.

Let’s get straight to the point:

var Days = new Enum([ 'Monday', 'Tuesday', 'Wednesday' ]); // to be continued

Usage:

var inputDay = Days.Monday;
return (inputDay === Days.Monday) // returns true

It provides a useful .toString() method:

console.log( Days.Monday.toString() ); // logs 'Monday'

It is also protected against overwriting by using Object.freeze. If you don’t want to freeze it, you can pass it as an option when you’re creating the enum:

var Days = new Enum([ 'Monday', 'Tuesday', 'Wednesday' ], { finalize: false });

enum.js is very small and has no dependencies. Grab the source code from the GitHub repo and start creating JavaScript enums today!

Understanding Backbone View Events

When you are using Backbone, you’ve surely heard of the useful DOM-bound events provided by Backbone.View. Here is an example of such an event:

var someView = Backbone.View.extend({

  el: 'section#content',

  events: {
    'click button#save':    'saveSomething'
  },

  saveSomething: function(event) {
    // do work
  }

});

These events work only if you’ve provided the ‘el’ attribute. It represents the current context of your view. Events also require jQuery, since it uses its $.on() method to bind events to the DOM.

How it actually works

Backbone first parses your input string with this regular expression:

/^(\S+)\s*(.*)$/

It breaks the string into two parts; The event name and the selector. Example:

click button#save

--> eventName: 'click'
--> selector: 'button#save'

That’s basically it. Now it just calls jQuerys $.on() like this:

this.$el.on(eventName, selector, method);

…and your event is bound to the DOM. As you can see, events can only be bound to elements within the context of your view (‘el’ attribute). This approach allows you to use any event that jQuery provides.

Events are automatically bound after the ‘render’ method. If you need to call it by hand, you can use delegateEvents.