
Step by step from jQuery to Backbone - kjbekkelund
http://open.bekk.no/from-jquery-to-backbone/
======
Robin_Message
I like the tutorial style and I wanted to show something like this to someone,
so that's really cool.

There's one thing I think you've got wrong in the example: by having functions
bound to the same event (addStatus and clearInput), you paint yourself into a
corner with Backbone, where you can only bind one function declaratively.
However, your solution of clearing the input whenever a status is added is
wrong, since (conceptually) the status collection may add statuses whenever it
likes for whatever reason, but now doing so will erase the user's input box.
Suppose this evolved into a realtime twitter-like thing – you would get hard
to understand bug reports of people's input "disappearing".

(Moralising: It's important not to let architecture astronautics distract form
the actual logic of the program.) When the NewStatusView successfully adds a
status, it should be responsible for clearing its input ready for reuse. The
call to clearInput belongs at the end of addStatus. A further argument for
this is that it will eventually have to move into a success callback of the
collection add, for example when a banned list of words in statuses lives on
the server, or you actually broadcast the statuses.

Don't know why I felt compelled to make such a long comment; hope it makes a
great reason even better.

~~~
kjbekkelund
Great point. I'll take a look at it and maybe make some changes. :)

------
geuis
This is an excellent tutorial. It's also an excellent lesson in why you should
stay away from frameworks like Backbone.

(To declare, I have written large apps with Backbone, so I'm not entirely
talking from my ass.)

You've gone from a simple, succinct, and easily understood set of code to
something that now relies on 2 extra frameworks (backbone and underscore), in
addition to still needing jQuery. You've had to incorporate several layers of
abstraction (views, cloning events) to simply do what was originally done in a
few lines.

I know what the appeal of something like Backbone is. You think that adding in
all this abstraction will make it easier to maintain your product. I will even
agree that to an extent, it does.

However, a big problem is that the people that already care about organizing
their code well, already do so. Backbone is so needlessly open-ended and
directionless that a dev who doesn't already know how to write good code will
just write worse code.

When I first learned Python, it was enlightening. Here was a language that
says, "This is the right way to do it". It got rid of the baggage of other
languages and got to business. Backbone is definitely not that for JavaScript
development.

Backbone gives you so much rope to hang yourself with, and with so little
sense of how things should properly fit together, that it's like wandering
around a desert for days on end with a noose on your neck, until you fall into
a deep enough hole and die.

I prefer to write my code so that there is an overall architecture, usually
with a modular pattern when possible. Anything that needs to happen code-wise
for a particular module is all contained within that code block and nothing
else. That code is more or less like what was originally posted, where all the
things that matter for that module are done in that module.

The other technique I use for modules to talk to each other is sheerly through
event signatures. If you have a login module, it can emit events like
"loggedin" or "loggedout". Any other module can subscribe to those events and
do their own thing, without interfering with others, etc.

This pattern works very well and is a hell of a lot more usable than anything
I've ever been able to do with Backbone.

Finally, Coffeescript is not JavaScript. It's another annoying abstraction.

JQuery is not JavaScript, but an incredibly useful library.

Stop piling one layer on top of another thinking you're making your life
easier. Get back to basics, learn how to structure your code, and just get
some fucking work done.

~~~
bherms
Finally someone who agrees with me. I like Backbone quite a bit and a large
part of our application is now using it... However, the added code, layers of
abstraction, and lack of any "right" way to do things make maintaining it more
of a hassle than anything else. I like that many people are trying to build
application frameworks on top of backbone (marionette, etc) but this is just
making things worse as now you have 20+ choices on how to write your backbone
application, thereby making it harder to maintain across developers (what are
the chances the new guy you hired is not only proficient in Backbone, but also
backbone using handlebars instead of underscore, and also backbone + chaplin
-- or vertebrae, or thorax?)

When our js guru started porting our app the backbone, it was intensely
difficult at first for the rest of our devs to make trivial changes to our
front end code. What used to be a well defined information flow was now spread
across dozens of files.

~~~
madoublet
Don't worry, there will soon be a movement to get back to POJOs (Plain Old
JavaScript Objects) and the cycle of engineers over-thinking a problem will be
reset.

------
kjbekkelund
Author here. The blog appears to be down, check it out on Github instead:
[https://github.com/kjbekkelund/writings/blob/master/publishe...](https://github.com/kjbekkelund/writings/blob/master/published/understanding-
backbone.md)

~~~
m_st
I can't say thank you enough! This is the first Backbone.js tutorial that
really made any sense to me.

------
DougWebb
Very well written tutorial, right up to this part:

 _However, the code has increased from 16 lines to more than 40, so why do I
think this is better? Because we are now working on a higher level of
abstraction. This code is more maintainable, easier to reuse and extend, and
easier to test. What I've seen is that Backbone.js helps improve the structure
of my JavaScript applications considerably._

I don't see any justification for those claims. In my experience, more code
means less maintainable, because it's more to understand and provides more
opportunities for bugs to creep in. I can look at the original 16 lines and
understand immediately what's going on, while the 40 line result doesn't even
fit onto my screen all at once, and the application logic is broken up and
spread out across a bunch of boilerplate-type code.

Regarding reuse and extensibility, I don't see that here either. Sure, you can
add more behavior when either element changes, but you could have done that
before just as well. For reuse, what's the likely-hood that you're going to
need a control like this, which seems to be tightly bound to the application
requirements? If you're writing a library or generic control reuse is
important, but most of the time most developers are writing custom one-off
requirement-specific controls, and reuse just isn't as important as clarity
and simplicity. Besides, if you _really_ wanted to reuse the original, you
could move it all into a function and pass 'new-status' and 'statuses' as
arguments; then any form/textarea/ul triplet can be used as a control.

Finally, testability: yes, I'll grant that your final version is more
scriptable which makes it easier to write automated tests. However, you've
also got a lot more to test, because now your code is subject to bugs in the
1000 lines of Backbone code you've made yourself dependent upon. What if there
is some problem in the communication with your service? That's buried in
Backbone and you're insulated from it, unlike in the original where $.ajax
gives you nearly direct control over all aspects of the communication. The
original, being much simpler, is also easier to visually inspect for bugs. Not
much can go wrong in 16 lines of tightly integrated code, but once you switch
over to inserting bits of behavior into a larger framework that you don't
control and probably don't understand, who knows when your code will get
executed (or not) and what edge cases might arise?

BTW, yes I know jQuery is a much larger and more complex dependency, but both
the original and final examples depend on it equally. More importantly, your
code calls jQuery rather than jQuery calling your code: your code stays in
control. With frameworks like Backbone, your code gives up control to the
framework.

~~~
kjbekkelund
Great feedback. What I mentioned are things I've seen from working on fairly
large JavaScript apps in enterprise environments. Maybe I should have made it
clearer that those where my experiences.

What I failed to note is that in my experience the end result has less code
and less complexity when writing my JavaScript like this.

~~~
crescentfresh
IMO what the Backbone.js version has over the jQuery [only] version is
readability in a large code base. I assume by "maintainability" this is one
thing you mean.

You're only going to cover a small example in a tutorial, so the above benefit
is not readily apparent.

~~~
DougWebb

       statement: {
    
           context: { opinion: "mine" },
    
           subject: "Backbone.js",
    
           type: new Comparison("jQuery [only] version"),
    
           filter: new FilterContext("large code base"),
    
           result: "readability",
    
           action: raise("assume", { subject: "maintainability" }),
       };
    
    
       on("assume") {
           belief: "one thing you mean"
       };
    
    

I disagree that this spread-out, boilerplate-rich format becomes more readable
the more of it that you have. I think the larger your codebase is, the more
important it becomes for distinct chunks of application logic and behavior to
be written clearly and concisely.

------
Jare
Very nice writeup, probably one of the best practical articles on
transitioning code to MVC-style structure.

My only question about the result is the binding of NewStatusView.clearInput
to the collection add event. If I understood correctly, it is logically
incorrect in that clearing the input field should be a result of having
submitted it, not of the fact that something has been added to the collection.
A typical example to illustrate this issue would be a collaborative
environment where multiple views/users can be adding to the same collection -
say, a chat. Every submit would clear everyone else's text fields mid-typing?

~~~
kjbekkelund
Thanks! And great question. Of course, in real-time environments you need to
be really sure which events trigger when. However, on a normal single-page app
the add event will only be triggered when you have make a request to the
server, and you won't do that mid-typing, only when you're finished typing.

Edit: But, of course, as Robin_Message mentions, it's not always as clear cut
as I stated, and there might be some issues with my solution.

------
dclowd9901
If the premise of this article is to teach Backbone to people who are
accustomed to jQuery, I think it fails miserably. It's long-winded, obtuse,
and the example, which is supposed to firmly anchor you, is hazy and
enigmatic.

The real trick of Backbone is treating it like a delegator for the UI. It
handles creation of new elements, interactions, and creates a 1:1 relationship
between the data and what is seen on screen; that's why it's so important in
single-page JS websites: It handles the gap between raw JSON data and page
visualization.

------
polshaw
As others have said, thanks, really great tutorial. I don't know whether i'm
going to go all the way to backbone (maybe?), but wherever i stop i'll have
better, more maintainable JS.

I also have a quick question; why from the 'Creating a view' section, why do
we have:

    
    
        var NewStatusView = function(options) {
            var statuses = options.statuses;
            ...
        
        new NewStatusView({ statuses: statuses });
    

instead of just calling `NewStatusView(statuses)` and having `var
NewStatusView = function(statuses){` ??

~~~
kjbekkelund
I've gradually started passing a hash instead when I expect the number of
arguments to increase, which I do for constructors (I hate reading code and
not understand the arguments in a function call). But also, it made the change
over to Backbone views easier and less "magic".

------
xiaoma
Now this is serendipitous! Earlier today while on my run, I was thinking about
finding a resource to take me to the next step after the codeschool
backbone.js series.

This is great, though I am having some doubts about whether backbone is the
way to go or if angular or ember would be a better choice to invest my time in
learning.

~~~
dylanz
After playing with them all, we went with Angular for what it's worth. Less
lines of code, IOC is pretty neat, and it just "feels good". We're happy w/
our choice thus far.

------
jasonkostempski
Really nice format. I've been using backbone for over a year and knew exactly
how the code was going to end up but my understanding of 'why' is better after
reading it, which is a really the most import question to answer. I hope this
style catches on, maybe the format could be called a Why-To :)

------
simonista
Thank you so much for writing this. I've always felt like I was missing
something with Backbone -- I knew that it was mostly infrastructure and
assumptions that helped organize and clean up client-side code, but coming
from mostly a backend/rails background, I never quite understood the
assumptions that were being made and the "magic" that has happening behind the
scenes. This step-by-step process is really helpful.

------
countessa
nice - like the presentation with the file diffs. awesome stuff.

~~~
mitjak
I noticed that as well. Stealing the idea for my own blog. Makes it very clear
what changed, which is instrumental during learning.

------
pindi
I really like this tutorial's format. I made another one in its spirit about
Agility.js, another framework that is significantly more succinct:
[http://www.pindi.us/blog/step-by-step-from-jquery-to-
agility...](http://www.pindi.us/blog/step-by-step-from-jquery-to-agility-js)

------
erik518
Is it just me or do these two apps not behave similarly at all? The jQuery app
posts a status to a URL, the Backbone one does not. If the intention was only
to show your typed status below once you click a button, why the Ajax call to
begin with? Again, maybe I missed the point entirely.

~~~
kjbekkelund
Ah, minor mistake. Used `add` instead of `create`. It's been fixed in the blog
post, and I'll push a fix to the app soon.

------
powatom
I've recently become a bit of a fan of Backbone, and have been tying it with
Vertx and SockJS. It makes my fingers tingly.

~~~
swah
Might I ask: how are you using those together?

~~~
swah
I'm asking because Backbone is written for CRUD apps out of the box, and real-
time webapps aren't CRUD normally.

------
chinchang
Very nice and innovative style and osom tutorial as well. If only one could
write this for spine as well :D

~~~
8ig8
The author of Spine wrote this book:
<http://shop.oreilly.com/product/0636920018421.do>

------
gaving
Really nice way of explaining things.

------
tilt
Very excellent read, thanks!

------
gorm
Very nice article! Thanks!

------
irishb
Github link 404s. :-(

~~~
kjbekkelund
Which Github link? This one:
[https://github.com/kjbekkelund/writings/blob/master/publishe...](https://github.com/kjbekkelund/writings/blob/master/published/understanding-
backbone.md) ?

------
Toshio
Nice tutorial.

I have a question: how come you aren't making use of _.bindAll?

~~~
kjbekkelund
Because I think it's cleaner having it as the third argument on events instead
of having a large list of stuff in _.bindAll in initialize (and additionally,
I've found it simpler to explain it to others, but I don't know why). I think
it's just one of those subjective choices.

~~~
epidemian
Agreed. Plus, bindAll [1] does quite a lot of magic under the hood that IMO is
an overkill compared to passing the context object.

[1]: <http://underscorejs.org/docs/underscore.html#section-52>

------
tubbo
HAHAHA nice IE 503 error...

------
beshrkayali
Well, the website is down... Thanks kjebkkelund

~~~
kjbekkelund
You can read it here:
[https://github.com/kjbekkelund/writings/blob/master/publishe...](https://github.com/kjbekkelund/writings/blob/master/published/understanding-
backbone.md)

Our Wordpress bullshit is failing hard.

~~~
beshrkayali
I found the link, awesome writeup :) Thanks!

