12 ms·
Backbone.js: Hacker's Guide
- tambourine_man 14y agoCould anyone show me what kind of problems Backbone.js solves? Not a description like “it will replace a lot of your jQuery spaghetti boilerplate”, but some actual code: //this is what I had to write in jQuery … … //this is how I'd do it in Backbone.js
- aroman 14y agoI'm not sure it lends itself to such contrived examples. A more useful comparison would be the use of backbone to build an entire web app (a small one). Backbone has a number of components and it's not exactly like you can have a three-line diff of the two to explicate the merits of one of the other. I'd look here: http://addyosmani.github.com/todomvc/ http://addyosmani.github.com/todomvc/ Check out the Backbone one and the jQuery one. They should basically be the same idea, suited to each of the two frameworks. Also, remember that Backbone and jQuery are not mutually exclusive (quite the contrary -- Backbone actually requires jQuery/Zepto). So you're sort of comparing Tangerines and Oranges.
- oleyb 14y agoThe problem Backbone.js solves is primarily that of structure and organization. It's not about replacing jQuery, its about how you organize that code and have a clearer separation of interface, data, and logic.
- politician 14y agoIf you want to "replace" jQuery, use a model binding library which takes care of driving the UI from the values set in the models. Check out the "Views" section for a list of libraries: https://github.com/documentcloud/backbone/wiki/Extensions%2C-Plugins%2C-Resources https://github.com/documentcloud/backbone/wiki/Extensions%2C...
- ajross 14y agoHere's my iconoclast answer (with a further caveat that I'm a systems programmer who follows web development in my spare time, not an expert on any of this): Backbone (or Spine, which is just like Backbone but a tiny bit smaller and written in CoffeeScript) is Yet Another MVC Framework. So think of it like Rails, except this time it runs in the client browser. So instead of translating between SQL and Ruby, you're translating between JSON and DOM. There's a "Model" abstraction, which is just a data structure but has fancy features like the ability to "save" it to the server and the ability to listen for changes. And there are "views", which are just the same old DOM/CSS/jQuery environment you know, with the single stipulation that they need to be associated with exactly one Model. And, just like rails, there are "Controllers" which all the guru's seem to understand just fine but that look like huge messy piles of logic soup to the rest of us. And, like all MVC frameworks before and after, it's subject to the framework disease. You don't "use" MVC, you "port to it". It infects everything you do, such that you get indoctrinated into the particular MVC subculture you've chosen and spend your time screaming at other people on the internet instead of writing code (edit: c.f. rimantas below.). Stay away. Or if you must use it, be sane and safe, and stay away from the culture.
- lazerwalker 14y agoBackbone doesn't actually have controllers, only models and views. Even without that technical distinction, I'd still be hard-pressed to actively describe Backbone as MVC (especially compared to other JS frameworks like SproutCore or Ember, which do actively force you into a more traditional MVC structure). It doesn't actively encourage you to structure your code in any particular way, other than "separate your business logic and DOM logic", which you probably want to be doing anyway if you're building the sort of JS-heavy rich web application that people tend to recommend Backbone for.
- sophacles 14y agoI have a couple apps that use backbone. * One is just a fancy web page, it uses Backbone in a traditional sort of MVC way. I don't use the router tho, doing my own thing with pushState and gradual enhancement. Lots of views and models keep things separated sanely. * Another uses it because I wanted an easy mechanism to map between storage and app. I think the only reason I used views in this case was because I had already been using a template, so I just threw it in a view to tie events together. * The last I don't use any of the "talk to the server" features, but use the event model because it allowed for easier reactive style stuff with events and forms, and tying into canvas frameworks than alternatives. The data model doesn't fit nicely with Backbone, so I did my own thing. The point is, Backbone keeps it easy to not get sucked into the whole model if you don't want to.
- tptacek 14y agoI had the same question after trying to use Backbone on a couple different small projects and giving up after seeing it introduce more complexity that I saw it removing. Recently, I discovered Knockout.js, which is a "competitor" to Backbone with what I think is a clearer interface and a much clearer value proposition. I've had a lot of success with Knockout and fully expect that, like Sinatra did to me with Rails, Knockout will teach me to appreciate Backbone soonish. In the meantime, here's the knockout pitch: What Knockout does is allow you to keep separate models (which are plain-old Javascript objects; Knockout doesn't need to infect them or enforce any kind of structure to them at all) and DOM UI. Knockout's job is to keep the two in sync. For instance, if you have an array of Foo's rendered in a table, Knockout allows you to bind a "foreach" to the table's body, effectively turning a single TR into a template for each Foo. Then, if the elements of the Foo array change dynamically, Knockout makes the table reliably reflect the constitution of the array. The core value here isn't "templating". It's "keeping the DOM in sync with Javascript objects". Off the top of my head, I think we're talking about 3 lines of code to get that functionality: the data-bind attribute on the TBODY element, the ko.observableArray() that wraps your otherwise plain array of Foos, and the ko.applyBindings(RootModel, RootDomElement) call that kicks off Knockout. The same functionality would probably cost 10-20 lines of jQuery; more importantly, that jQ code would be fiddley, not at all declarative, and duplicated every place you wanted to bind an array to some repeating DOM structure. Knockout is here, to my eyes, a clean win. Or take forms: you bind (with data attributes) INPUT elements to Javascript objects, so that what their values are changed by user input, the Javascript objects automatically reflect their new values. The JS code that then cares about the value of these objects doesn't ever need to scrape out the values of forms, and can reliably assume whatever's in the fields or hashes or whatever you set up is going to be current input. Also: you can bind multiple form inputs to the same data and keep them in sync, which I found to be a pleasant way to implement an "Advanced Search" feature. What I didn't like about Backbone was the notion it had of "Models" and "Routers" and stuff like that. I'm sure that's valuable structure to have, but I like the flexibility --- and, more importantly, the freedom for More Stuff I Have To Memorize --- that comes with the KO.js approach.
- espeed 14y agoRecently I discovered AngularJS (http://angularjs.org http://angularjs.org) by some of the guys at Google. I spend most of my time on the backend and have never been a fan of JavaScript, but the AngularJS declarative design really caught my eye. It's so clean and so simple. I think it's brilliant. See http://www.youtube.com/watch?v=elvcgVSynRg http://www.youtube.com/watch?v=elvcgVSynRg
- epidemian 14y agoYou can compare the TODO list implementations in todomvc: Backbone: https://github.com/addyosmani/todomvc/tree/master/architecture-examples/backbone https://github.com/addyosmani/todomvc/tree/master/architectu... jQuery: https://github.com/addyosmani/todomvc/tree/master/architecture-examples/jquery https://github.com/addyosmani/todomvc/tree/master/architectu... The Backbone implementation is an adaptation of this: http://backbonejs.org/docs/todos.html http://backbonejs.org/docs/todos.html which i think is more readable. The todomvc adaptation is a little over-structured for my taste, too many JS files for too little functionality.
- knowtheory 14y agojashkenas went over a lot of this in the State of the Backbone at Backboneconf. Regretfully you can't see all of the examples in the video... but you can hear his description here: http://blog.documentcloud.org/blog/2012/06/state-of-the-backbone/ http://blog.documentcloud.org/blog/2012/06/state-of-the-back...
- petercooper 14y agohttp://www.youtube.com/watch?v=yDmRRJzTo38 http://www.youtube.com/watch?v=yDmRRJzTo38 did OK with getting some of the examples in. No idea how they grew the arm of steel for holding that iPhone up though..!
- jashkenas 14y agoSure thing. But first, for the "kinds of things" that Backbone helps with, take a quick scroll through the list of examples available here: http://backbonejs.org/#examples http://backbonejs.org/#examples Here's a bit of typical (if exaggerated) jQuery to render/update the UI for a list of "accounts": $(".account").each(function(){ var id = $(this).attr('data-id'); var data = window.accountJSON[id]; $(this).find(".name").text(data.name); for (var i = 0, l = data.emails.length; i < l; i++) { var e = data.emails[i]; $(this).append($("<div class='email'></div>").text(e)); } var addresses = $(this).find(".address").length; $(this).find(".address_count").text(addresses); }); ... note that we're looking into specific DOM classes, pulling data from a big 'ol global JSON object, looking up id values from the DOM, and so on. Here's something a little bit closer you really want to write instead: Accounts.each(function(account) { new AccountView({model: account}); }); For each account, render its UI. Of course, this is just sweeping a lot of the complexity of the original example under the rug -- but that's the point -- you want your UI in HTML templates, and your data/model logic to be in "clean" JavaScript code unpolluted by UI concerns. Then, when you refactor your design later, all of your client-side business logic doesn't have to change -- it no longer cares about global nested JSON structures or concrete DOM elements. For another Backbone example, imagine taking all of the songs by a given artist, and rating them with 5 stars: Songs.each(function(song) { if (song.get('artist') == "Wire") { song.set({stars: 5}); } }); ... and your UI updates accordingly, and you can change that ".set" to a ".save" call to persist the tracks back to your server as well.
- kevincennis 14y agoAsk and ye shall receive. An answer from the library author. Doesn't get much better than that.
- tambourine_man 14y agoThanks a lot jashkenas. I have to admit that whenever I see “MVC something” a lazy instinct kicks in. Probably because it seems like an overkill and I know I can code something in a few minutes (which is never true) that will do the same without having to learn it. Usually, learning is most fun for me when I have a problem to solve or when I get really curious about something. And that song example falls in the second category.
- deleted 14y ago[deleted]
- tjholowaychuk 14y agoIMO it's not so much that frameworks need to solve these things, it's that you should be wrapping this sort of functionality in a more declarative way regardless, some devs either don't think about this at all or let it get out of control. I fully agree with Jeremy that you should not be using jQuery directly, I can't think of any case where it could not, or should not be abstracted out, jQuery is just the DOM helper. I like bits of backbone but I wish they were decoupled so you could just take the bits you wanted
- grungleshnorts 14y agoI found this talk from BackboneConf helpful: http://opensoul.org/blog/archives/2012/05/16/the-plight-of-pinocchio/ http://opensoul.org/blog/archives/2012/05/16/the-plight-of-p... It basically expands on what Jeremy said.
- malandrew 14y agoIf you want to see a large production app built in backbone simply fire up Firefox and go to: http://www.documentcloud.org/public/search/?debug_assets=true http://www.documentcloud.org/public/search/?debug_assets=tru... and save the source code and read through it. The debug_assets flag will return the entire unminified code.
- deleted 14y ago[deleted]
- netghost 14y agoIn case anyone's curious I came across this post about using Backbone for rich command line app: http://tobyho.com/2012/07/19/backbone-charm-text-based-ui http://tobyho.com/2012/07/19/backbone-charm-text-based-ui Pretty neat, I would never have thought of using it outside the browser.