

Migrating a large JavaScript project from DOM spaghetti to Backbone.js - conesus
http://www.ofbrooklyn.com/2012/11/13/backbonification-migrating-javascript-to-backbone/

======
hasenj
Backbone.js is not going to solve your DOM spaghetti problems.

You will still bind to events, you will still manipulate the DOM, you will
still do all the manual work.

I really recommend looking at Knockout.js instead.

It _really_ gets rid of all the DOM manipulation code that tends to become so
complex and spaghetti like.

How? It provides a declarative language for two-way binding between the UI and
the data.

Check out this example: <http://jsfiddle.net/FEVbz/>

In the HMTL pane, edit the input boxes and watch as the other DOM elements
update automagically.

Notice how simple and clean the Javascript code is. All it's doing is
initialization and setup. Nothing else. No event binding. No dom manipulation.
No spaghetti. No nothing.

Shameless plug:

Here's an article I wrote about why I think Knockout.js is _so_ much better
than Backbone.js

<http://dev.hasenj.org/post/35572197519>

~~~
rimantas
For anyone tempted: keep in mind, how trivial this example is. When time comes
to nontrivial things knockout will bite and bite you hard.

~~~
hasenj
As opposed to Backbone, which doesn't bite you hard?

Dude Backbone _only_ works for trivial examples, and even then, and I mean,
even with trivial examples, Backbone is almost useless.

I haven't yet been bitten by Knockout in any bad way.

~~~
Cthulhu_
"Dude Backbone only works for trivial examples, and even then, and I mean,
even with trivial examples, Backbone is almost useless."

I disagree. Backbone is a structuring framework; if you can't make it work
with bigger projects, you're doing it wrong.

------
lapusta
Backbone is a great framework and moved the industry forward a lot in terms of
code quality. But there are definitely couple things broken, like Zombie/Ghost
views - everyone(!) is making their own workaround.

View part is too much DIY. Seriously, _.template is okay for views with no
input and simple updates, but if you have heavy IO views become bloated. Check
the wiki, there are 7 "yet another binding plugins". Make default one, and
make it an option (view binding can be slow and not needed sometimes).

Another DIY are models relations & nesting. These two additions wouldn't be
big for the core, but they could really improve the ecosystem. Now you have to
take in mind those third-party plugins people are using for these covering
basic gaps.

~~~
timc3
So what do you suggest?

~~~
riprock
I haven't used Backbone.js, but from what I've read there are extensions like
Backbone.Marionette for better view and memory management.

<https://github.com/marionettejs/backbone.marionette>

~~~
randall
As obviously stated in other threads... I've moved to Angular. Their 'digest
all the changes and update the dom once' makes a lot of sense... and it has
basically inverse opinion from Backbone. (Backbone has lots of opinion about
data / saving, while Angular has more opinion about binding and logic.)

------
nateabele
Wow. After using AngularJS for a few months, it's amazing what a nightmare it
looks like to work with Backbone.

~~~
ww520
How is AngularJS compared to Knockout?

~~~
hasenj
Angular is more of a framework than a library. You have to do everything the
Angular way or things will become very difficult.

In trying to learn it, I found it quite complex (beyond the basic hello world
examples).

~~~
nachteilig
It's kind of interesting that we've almost developed an expectation of
JavaScript being simple. It's easy to forget what a pain it was to write
cross-browser JS even 5 years ago. I like this progress.

------
typicalrunt
Seeing the slide about one file that had 8500 lines in it surprised me. Maybe
it's a JS thing (I'm not one of those guys) but I've been pushed to make
smaller files instead of one large god file. It's hard to traverse a file with
that many lines in it, as well as do any meaningful diffs on it.

~~~
eta_carinae
There is no easy way to include .js file that are stored on your server.

~~~
sheraz
I've been using PHP Minify [1], a simple script to concatenate, minify, and
send out my backbonejs project.

Works well.

[1] - <https://github.com/mrclay/minify>

~~~
eta_carinae
That doesn't address my point, which was about includes at runtime of .js
files.

The reason why you see big .js files is that it's not easy to split your code
in a.js and have it include b.js from the server.

------
tjholowaychuk
Nothing wrong with backbone, but I do find it hilarious how it took a lib
creating faux classes to get people to stop writing hideous code, you can
write clean code with or without Backbone, and it'll look nearly identical.
Cleanliness is not in a framework, it's in your head.

~~~
glassx
I notice the same thing with Rails vs Sinatra. People complain that Sinatra is
problematic because it doesn't enforce a directory structure, but you can
still make clean, organized code with it.

------
rhysbb
Reading this just makes me scared of Backbone for larger projects. Things like
having to keep changes to models silent just because a view isn't ready?
Backbone is all good and well for small projects, but I think it's be best to
look elsewhere for a larger project. The problem is that backbone has a
smaller learning curve so people try to get started with it, and it is better
than nothing, but in the long run you'll just run in to more dead ends and
spend more time on fixing things and getting around edge cases than if you
went for a more fully fledged solution like <http://emberjs.com> or
<https://github.com/rhysbrettbowen/PlastronJS>

~~~
mattdawson
> Backbone is all good and well for small projects, but I think it's be best
> to look elsewhere for larger projects.

This is such ridiculous FUD, and I'm surprised every time I hear it. Compare
the apps built with Backbone section of their site against similar lists of
any competing framework. There are some seriously complex apps there. More big
ones than any competitor.

Just because a framework is minimal doesn't make it ill suited for large
projects. That goes for _all_ frameworks, not just js ones. And yet I see this
argument trotted out against minimalist frameworks in every language I work
in.

~~~
jashkenas
Amen, amen, 100 times amen. It's a real tragedy that this particular line of
FUD has caught on, but hey -- so it goes.

Links, for the curious:

<http://backbonejs.org/#examples>

<http://builtwith.angularjs.org>

<http://knockoutjs.com/examples/>

~~~
ludwigvan
Here is some more FUD for you (
[http://www.thoughtworks.com/articles/technology-radar-
octobe...](http://www.thoughtworks.com/articles/technology-radar-october-2012)
):

"Backbone.js is a great example of an abstraction pushed too far. While we
initially liked the ease of wire-up, in practice it suffers from the same
issues as all such data-bound frameworks from WebForms to client/server tools.
We find that it blurs the framework and model too much, forcing either bad
architectural decisions or elaborate framework hackery in order to preserve
sanity.

As the industry shifted from desktop GUI development to the web, it seemed
natural to port the most successful patterns and designs to the new paradigm.
After 15 years of trying, we feel that there are still no component-based
frameworks that have successfully achieved this. We recommend not attempting
to make web development into something that it fundamentally is not. It is
time to accept the page and request-based nature of the web, and focus on the
frameworks that support - rather than work against - these concepts."

This is diametrically opposed to my experience, and I'm really surprised by
the stance of ThoughtWorks on the matter. Hope I'm not doing a disservice by
spreading the FUD. My belief is that most of the competing JavaScript
frameworks are abstractions (and magic) pushed too far.

~~~
birowsky
I'm gonna be puking all day because of that quote.

------
bryanh
This is wonderful! I especially like the detailed coverage of Backbone views.
They tend to be the most perplexing part of Backbone (do I nest? how much? how
do I track them? etc...) and you outlined your use case nicely.

~~~
owenjones
Agreed. Even as someone who feels pretty comfortable in Backbone this was a
good exploration.

------
Kiro
I use jQuery a lot but Backbone is like Greek to me and so is every tutorial
I've seen. I just don't get it and I fail to see the benefits.

Can someone point me toward a good and simple explanation/tutorial?

~~~
uptown
I'm going through the same thing. I just got a small application up and
running using Backbone.js yesterday, but it still feels like a more-complex
application could get messy.

I did have one question regarding redundancy - if I take advantage of
something like validation with Backbone, I still need to do the same
validation on the server-side for any data that I POST or PUT back to the
server since I can't trust what comes from the client. Is the only gain from
doing the client-side validation in Backbone the faster feedback to the user
without requiring a round-trip to the server?

I'm currently trying to decide between Backbone.js, Angular.js, Ember.js or
sticking closer to what I know with a jquery pjax solution.

~~~
mcgwiz
The primary gain is faster feedback, but this can also reduce server load. In
general, you should never trust user input, so you should validate on the
server. (In particular, not only is it possible for users to
manipulate/disable your client code, including validation logic, but it's
trivial to hand-craft requests to your server.)

------
modarts
As someone about to embark on a large-scale project re factoring to backbone:

Thank you!

------
mcs
Awesome.

I would suggest using something like <https://github.com/afeld/backbone-
nested> to enable a.get('foo.bar.foo') so you don't have to
a.get('foo').bar.foo and suffer undefined errors.

~~~
codewright
[http://en.wikipedia.org/wiki/Monad_(functional_programming)#...](http://en.wikipedia.org/wiki/Monad_\(functional_programming\)#The_Maybe_monad)

It shouldn't have to be a library with custom handling of the edge cases like
that :|

~~~
oinksoft
It is pretty common to use a function like this when digging into objects in
general JS code:

    
    
      function get(p, o) {
        var parts = p.split('.');
      
        for (var i = 0, l = parts.length; i < l; i++)
          if (o.hasOwnProperty(parts[i]))
            o = o[parts[i]];
          else return undefined;
      
        return o;
      }
      
      var o = { a: { b: { c: 1 } } };
      
      console.log(get('a.b.c', o));  // 1
      console.log(get('no.way', o)); // undefined
    

I'd be more likely to reuse something like that because it's already useful in
the codebase than bringing on another library.

However, I am speaking out of ignorance, as it appears that the library you
cite does a lot more than this simple thing:
[https://github.com/afeld/backbone-
nested/blob/master/backbon...](https://github.com/afeld/backbone-
nested/blob/master/backbone-nested.js#L202)

In any case safe lookup methods are very useful!

~~~
codewright
Not very composable or nice. Bespoke solutions are besides the point and the
very thing I was decrying.

~~~
jQueryIsAwesome
Yeah, is one of the things I don't like about JS. The _typeof_ operator should
be able to handle those cases. Or a new operator that returns a boolean would
be nice.

    
    
        if(defined jQuery.unknown.propierties)

------
hamdiakoguz
I clearly see that backbone version is better. But i wonder if is it just me
that thinks there must be a better way than the event driven nature of
backbone ?

~~~
rhysbb
there are better frameworks out there for larger projects definitely - but
event driven is the best way for larger projects.

------
bjhoops1
Great post! Only suggestion I might add as a helpful pattern would be
leveraging Backbone.Events to implement a Mediator pattern for communication
between Views. This is overkill for between Parent Views and SubViews, but I
have found it to be very useful in facilitating communication between
unrelated Views.

------
kylecordes
From the blog post and slides, it looks like this was a big improvement.

But...

You may find that moving to a higher level, more declarative solution (like
Knockout) yields a considerable additional improvement.

~~~
skeletonjelly
I thought Knockout and Backbone were two implementations fixing the same
problem. Can you expand?

~~~
rimantas
Unless something changed drastically changed in the last year my impression
was this: Backbone helps you to fix problem, Knockout just hides it. I think
some people just have a problem with backbone being too flexible, because it
matches the name perfectly: it is just backbone helping you to solve problems
you will have to solve anyway.

Knockout feels more like exoskeleton — it may be very comfortable when you fit
in, but as soon as you don't you are in a lot of pain.

~~~
modarts
I could imagine data binding geting _very_ hairy to develop more complex apps
with.

------
gambler
I never understood why people proudly boast about their past mistakes. Is it
supposed to make their current achievements sound better? "Oh, we had 8500
lines of spaghetty JS code in one file, but we used AwesomeFrameworkX and it
fixed everything!" For me, this doesn't make the framework sound more
impressive, but rather undermines credibility of the author. How did it get to
8.5 lines? Did no one notice? Did no one care? Was every line necessary? Does
having a file like that is really better than having some stuff handled on the
server side? Was Backbone the only way to move forward?

~~~
justinator
No one's perfect and we all make mistakes, given the circumstances we find
ourselves in - we all make choices with incomplete information.

Admitting that there's a better way to do things is a good first step to
become better. To share what you've learned is a sign of being humble.

~~~
gambler
We all make mistakes, but not all of us use those mistakes to promote
something. It's an annoying and overused software evangelism trick. You start
by decrying your past ignorance, and continue by saying that you were
enlightened and started using X. This dramatizes the improvement and subtly
implies that everyone who doesn't yet use X are simply not yet as enlightened
as you. There is nothing genuinely humble about doing this.

~~~
cnp
(...)

------
OriginalSyn
Thanks Samuel, this was the best talk at the summit.

------
salimmadjd
Great post! I wish you had briefly talked about why you picked backbone over
other options like AngularJS.

~~~
conesus
I'll admit, partially it was because I was sitting next to Jeremy as he was
pulling backbone out of the documentcloud workspace and into a soon-to-be-
released javascript library. Otherwise, the community has embraced Backbone.js
and, for better or for worse, you're swimming in the biggest pond. That means
more community driven updates and support, as well as more competition to
stand out from in the newest javascript writing convention.

