Thursday, August 22, 2013

Backbone.js and Two Dumb Idioms

I've been learning Backbone.js which is MVC (or MV*) for client-side JavaScript.

In Backbone.js, you define a model (the "M") by doing this:

var Model1 = Backbone.Model.extend({
});

You create an instance of a model by doing this:

var model1 = new Model1();

To define a Backbone.js view (the "V"), you can do something like this:

var View1 = Backbone.View.extend({
  events: {
    click: function(e) {
      alert('Clicked!');
    }
  }
});

To create an instance of the view, you can do this:

<a id="a1" href="#"><span>My Link</span></a>
...
var view1 = new View1({el: '#a1'});

Now, here comes Dumb Idiom #1.  You can do this:

alert(view1.$el.css('display'));

Say what?  What's view1.$el?  It's a dumb shorthand that saves two characters.  It means $(view1.el) in regular old jQuery but instead of typing those two parentheses, you can use a shortcut that only works in Backbone.js and easily throws everybody, including yourself, for a loop.

But, wait, there's more.  Here comes Dumb Idiom #2.  Instead of using jQuery find(), you can do this:

alert(view1.$('span').html());

What is this?  In Backbone.js but not standard jQuery, you can use view1.$('span') as a shorthand for $(view1.el).find('span').  We save a few more characters here (i.e. nine) but pay for it with the need to memorize yet another idiom.

Backbone.js, stick to your knitting!  You aren't jQuery and shouldn't be inventing unnecessary and non-standard idioms for jQuery.