ChatGPT解决这个技术问题 Extra ChatGPT

What is the purpose of backbone.js?

I tried to understand the utility of backbone.js from its site http://documentcloud.github.com/backbone, but I still couldn't figure out much.

Can anybody help me by explaining how it works and how could it be helpful in writing better JavaScript?

It's a MVC framework. It encourages you to abstract your data into models and your DOM manipulation into views and bind the two together using events.
How can a "view" handle events with in the context of MVC? This is what backbonejs.org claims in their introduction.
It's worth learning. I had a hard time getting started, but after getting over a few humps in the learning curve it's really not too hard. Start with the Wine Cellar demo.
Within the context of Backbone, the view kind of doubles up as a controller. It listens to DOM events and chucks them up to the models as appropriate. It also listens for changes to your models and collections and redraws the DOM appropriately. Backbone is an MV pattern, but the C is implied. If Backbone were Rails, the template would be the view, and the view would be the controller.
I thought it's a MVVM framework as it doesn't actually provide controllers.

J
JJJ

Backbone.js is basically an uber-light framework that allows you to structure your Javascript code in an MVC (Model, View, Controller) fashion where...

Model is part of your code that retrieves and populates the data,

View is the HTML representation of this model (views change as models change, etc.)

and optional Controller that in this case allows you to save the state of your Javascript application via a hashbang URL, for example: http://twitter.com/#search?q=backbone.js

Some pros that I discovered with Backbone:

No more Javascript Spaghetti: code is organized and broken down into semantically meaningful .js files which are later combined using JAMMIT

No more jQuery.data(bla, bla): no need to store data in DOM, store data in models instead

event binding just works

extremely useful Underscore utility library

backbone.js code is well documented and a great read. Opened my eyes to a number of JS code techniques.

Cons:

Took me a while to wrap my head around it and figure out how to apply it to my code, but I'm a Javascript newbie.

Here is a set of great tutorials on using Backbone with Rails as the back-end:

CloudEdit: A Backbone.js Tutorial with Rails:

http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/

http://www.jamesyu.org/2011/02/09/backbone.js-tutorial-with-rails-part-2/

p.s. There is also this wonderful Collection class that lets you deal with collections of models and mimic nested models, but I don't want to confuse you from the start.


another usefull tutorial : coenraets.org/blog/2012/01/…
This answer is wrong. Backbone is not an MVC framework. It is an MV* framework. Understanding the main components is kind of important. And it does not have Controllers. Good luck.
Just to reiterate, the Backbone library itself does not have controllers, though Jeremy Ashkenas has said that View objects kind of take their place since they are JavaScript objects that own models and shuffle data to and from the front end. There is of course nothing to stop you from implementing a Controller, a Service, even a ViewModel should you so wish, it's just JavaScript.
What's JAMMIT? ɯnɯıuıɯ ʇunoɔ ɹǝʇɔɐɹɐɥɔ
RE: "jQuery.data(bla, bla): no need to store data in DOM" IIRC, jQuery stores that in-memory anyway. i.e. it does not set data- attributes back onto the DOM elements. (So if your HTML had data- attributes when the page loaded, and they are changed, the DOM and the in-memory representation would be OOS - but you should be working with the in-mem data anyway)
J
John Munsch

If you're going to build complex user interfaces in the browser then you will probably find yourself eventually inventing most of the pieces that make up frameworks like Backbone.js and Sammy.js. So the question is, are you building something complicated enough in the browser to merit using it (so you don't end up inventing the same thing yourself).

If what you plan to build is something where the UI regularly changes how it displays but does not go to the server to get entire new pages then you probably need something like Backbone.js or Sammy.js. The cardinal example of something like that is Google's GMail. If you've ever used it you'll notice that it downloads one big chunk of HTML, CSS, and JavaScript when you first log in and then after that everything happens in the background. It can move between reading an email and processing the inbox and searching and back through all of them again without ever asking for a whole new page to be rendered.

It's that kind of app that these frameworks excel at making easier to develop. Without them you'll either end up glomming together a diverse set of individual libraries to get parts of the functionality (for example, jQuery BBQ for history management, Events.js for events, etc.) or you'll end up building everything yourself and having to maintain and test everything yourself as well. Contrast that with something like Backbone.js that has thousands of people watching it on Github, hundreds of forks where people may be working on it, and hundreds of questions already asked and answered here on Stack Overflow.

But none of it is of any importance if what you plan to build is not complicated enough to be worth the learning curve associated with a framework. If you're still building PHP, Java, or something else sites where the back end server is still doing all the heavy lifting of building the web pages upon request by the user and JavaScript/jQuery is just icing upon that process, you aren't going to need or are not yet ready for Backbone.js.


Thanks for the comparison to Gmail. That was an easy way for me to figure out I don't need to look further into this for the site I'm developing.
+1 for mentioning that you'll end up writing something like backbone.js yourself anyway if your project gets big enough: re Greenspan's 10th Rule
If you're using PHP or anything similar just as an endpoint for a web service then you're not using 80 or 90% of traditional request/response style web development framework. So there's a big difference in how this kind of app ends up being built vs. a more traditional web app.
Thanks John For Your Answer its really Enlightning
The Gmail reference really opened my eyes. Thanks!
d
drac_o

Backbone is...

...a very small library of components which you can use to help organise your code. It comes packaged as a single JavaScript file. Excluding comments, it has less than 1000 lines of actual JavaScript. It's sensibly written and you can read the whole thing in a couple of hours.

It's a front-end library, you include it in your web page with a script tag. It only affects the browser, and says little about your server, except that it should ideally expose a restful API.

If you have an API, Backbone has a few helpful features that will help you talk to it, but you can use Backbone to add interactivity to any static HTML page.

Backbone is for...

...adding structure to JavaScript.

Because JavaScript doesn't enforce any particular patterns, JavaScript applications can become very messy very quickly. Anyone who has built something beyond trivial in JavaScript will have likely run up against questions such as:

Where will I store my data? Where will I put my functions? How will I wire my functions together, so that they are called in a sensible way and don't turn to spaghetti? How can I make this code maintainable by different developers?

Backbone seeks to answer these questions by giving you:

Models and Collections to help you represent data and collections of data.

Views, to help you update your DOM when your data changes.

An event system so that components can listen to each other. This keeps your components de-coupled and prevents spaghettification.

A minimal set of sensible conventions, so developers can work together on the same codebase.

We call this an MV* pattern. Models, Views and optional extras.

Backbone is light

Despite initial appearances, Backbone is fantastically light, it hardly does anything at all. What it does do is very helpful.

It gives you a set of little objects which you can create, and which can emit events and listen to each other. You might create a little object to represent a comment for example, and then a little commentView object to represent the display of the comment in a particular place in the browser.

You can tell the commentView to listen to the comment and redraw itself when the comment changes. Even if you have the same comment displayed in several places on your page all these views can listen to the same comment model and stay in sync.

This way of composing code helps to keep you from getting tangled even if your codebase becomes very large with many interactions.

Models

When starting out, it's common to store your data either in a global variable, or in the DOM as data attributes. Both of these have issues. Global variables can conflict with each other, and are generally bad form. Data attributes stored in the DOM can only be strings, you will have to parse them in and out again. It's difficult to store things like arrays, dates or objects, and to parse your data in a structured form.

Data attributes look like this:

<p data-username="derek" data-age="42"></p>

Backbone solves this by providing a Model object to represent your data and associated methods. Say you have a todo list, you would have a model representing each item on that list.

When your model is updated, it fires an event. You might have a view tied to that particular object. The view listens for model change events and re-renders itself.

Views

Backbone provides you with View objects that talk to the DOM. All functions that manipulate the DOM or listen for DOM events go here.

A View typically implements a render function which redraws the whole view, or possibly part of the view. There's no obligation to implement a render function, but it's a common convention.

Each view is bound to a particular part of the DOM, so you might have a searchFormView, that only listens to the search form, and a shoppingCartView, that only displays the shopping cart.

Views are typically also bound to specific Models or Collections. When the Model updates, it fires an event which the view listens to. The view might them call render to redraw itself.

Likewise, when you type into a form, your view can update a model object. Every other view listening to that model will then call its own render function.

This gives us a clean separation of concerns that keeps our code neat and tidy.

The render function

You can implement your render function in any way you see fit. You might just put some jQuery in here to update the DOM manually.

You might also compile a template and use that. A template is just a string with insertion points. You pass it to a compile function along with a JSON object and get back a compiled string which you can insert into your DOM.

Collections

You also have access to collections which store lists of models, so a todoCollection would be a list of todo models. When a collection gains or loses a model, changes its order, or a model in a collection updates, the whole collection fires an event.

A view can listen to a collection and update itself whenever the collection updates.

You could add sort and filter methods to your collection, and make it sort itself automatically for example.

And Events to Tie It All Together

As much as possible, application components are decoupled from each other. They communicate using events, so a shoppingCartView might listenTo a shoppingCart collection, and redraw itself when the cart is added to.

shoppingCartView.listenTo(shoppingCart, "add", shoppingCartView.render);

Of course, other objects might also be listening to the shoppingCart as well, and might do other things like update a total, or save the state in local storage.

Views listen to Models and render when the model changes.

Views listen to collections and render a list (or a grid, or a map, etc.) when an item in the collection changes.

Models listen to Views so they can change state, perhaps when a form is edited.

Decoupling your objects like this and communicating using events means that you'll never get tangled in knots, and adding new components and behaviour is easy. Your new components just have to listen to the other objects already in the system.

Conventions

Code written for Backbone follows a loose set of conventions. DOM code belongs in a View. Collection code belongs in a Collection. Business logic goes in a model. Another developer picking up your codebase will be able to hit the ground running.

To sum up

Backbone is a lightweight library that lends structure to your code. Components are decoupled and communicate via events so you won't end up in a mess. You can extend your codebase easily, simply by creating a new object and having it listen to your existing objects appropriately. Your code will be cleaner, nicer, and more maintainable.

My little book

I liked Backbone so much that I wrote a little intro book about it. You can read it online here: http://nicholasjohnson.com/backbone-book/

I also broke the material down into a short online course, which you can find here (archived). You can complete the course in about a day.


Doesn't the View technically render a Template, not actually 'itself'? It seems to play more of the 'Presenter' or 'ViewModel' role.
Good point, though the view can render anything you ask it to. This could be a template, some arbitrary jQuery, or even something tiny like a value in a form, or a number in a badge.
That's true - especially because it's javascript, the boundaries are sorta smoke and mirrors - if you want to cross them inappropriately you can. When I first picked up backbone coming from more strict languages & MV(c/*) frameworks, that was one of the biggest hurdles when learning by example.
@superluminary reallly helps!!
The book is very helpful. Thanks for writing it.
d
dpan

Here's an interesting presentation:

An intro to Backbone.js

Hint (from the slides):

Rails in the browser? No.

An MVC framework for JavaScript? Sorta.

A big fat state machine? YES!


A
Andrew Hare

Backbone.js is a JavaScript framework that helps you organize your code. It is literally a backbone upon which you build your application. It doesn't provide widgets (like jQuery UI or Dojo).

It gives you a cool set of base classes that you can extend to create clean JavaScript code that interfaces with RESTful endpoints on your server.


I use jQuery and mootools and general javascript heavily on my project. How learing backbone.js will help me and what is Restful endpoint.Sorry if my question doesnt makes sense.
jQuery is mainly for DOM Manipulation where as Backbone is heavily used as an event driven framework as well as being used for modelling data.
s
sv_in

JQuery and Mootools are just a toolbox with lot of tools of your project. Backbone acts like an architecture or a backbone for your project on which you can build an application using JQuery or Mootools.


yeah actually its easy to assume the name is just a name for example 'jquery' presumably means 'javascript query' which really doesn't imply much by itself. But in this case its quite literally means backbone :)
V
Vince

This is a pretty good introductory video: http://vimeo.com/22685608

If you are looking for more on Rails and Backbone, Thoughtbot has this pretty good book (not free): https://workshops.thoughtbot.com/backbone-js-on-rails


u
user1415445

I have to admit that all the "advantages" of MVC have never made my work easier, faster, or better. It just makes the whole codeing experience more abstract and time consuming. Maintenance is a nightmare when trying to debug someone elses conception of what separation means. Don't know how many of you people have ever tried to update a FLEX site that used Cairngorm as the MVC model but what should take 30 seconds to update can often take over 2 hours (hunting/tracing/debugging just to find a single event). MVC was and still is, for me, an "advantage" that you can stuff.


Honestly any framework structure can be mutilated and deformed by ignorant programmers or programmers that just don't give a care. I once worked on a CodeIgniter site that should have been very straightforward and simple to build. But the idiot I worked with was so used to doing things the 90's way that he changed it from a clean OOP approach to a deformed procedural approach within OOP.
I have also seen someone write a site from scratch and write it beautifully without using any frameworks. On one occasion this was done by a relatively new/green PHP programmer. He just happened to have a very rational mind that worked out a pretty slick way to implement things. Using a good framework will only get you so far. Whereas using great programming practices will take you light years into the future.
@user1415445: What you say essentially means that having one single class that handles data logic, rendering logic, and communication between presentation layer widgets and data storage/retrieval code is easier to maintain than having each of these concerns handled by separate classes/objects. Which is hard to believe. Unless you could demonstrate a non-trivial app written twice, once with MVC and once without, that its non-MVC version is easier to maintain, etc.
Any application beyond the trivial ideally needs a pattern, and MVC is an excellent pattern when you're dealing with the presentation of data. It sounds like you've had a bad experience, but that's not the fault of the pattern.
documentation will always be the missing rosetta stone, no matter the patterns & practices used, because those change over time. the beauty of patterns like MVC is that once you understand the plumbing, you never have to waste time writing plumbing every time you add a new feature or update an old one. So yes, until you understand the plumbing, it will be an exercise of futility. The only way to ensure adequate understanding of future unknown devs is follow reasonable enough standards AND ALSO document well. Maintaining and understanding someone's spagettified mess is not faster or easier..
J
JJJ

Backbone was created by Jeremy Ashkenas who also wrote CoffeeScript. As a JavaScript-heavy application, what we now know as Backbone was responsible for structuring the application into a coherent code base. Underscore.js, backbone's only dependency, was also part of the DocumentCloud application.

Backbone helps developers manage a data model in their client-side web app with as much discipline and structure as you would get in traditional server-side application logic.

Additional benefits of using Backbone.js

See Backbone as a library, not as a framework Javascript is now getting organized in a structured way, the (MVVM) Model Large user community


d
drac_o

backbone.js is Model-View-Controller (MVC) with JavaScript but Extjs (archived) better than backbone for MVC Pattern by java script

With backbone you got freedom to do almost anything you wish for. Rather than trying to fork through the api and customize I would use Backbonejs for it's simplicity and ease of implementation. Again it is hard to say what you require out of the two one is a library another a component


b
benvds

It also adds routing using controllers and views with KVO. You'll be able to develop "AJAXy" applications with it.

See it as a lightweight Sproutcore or Cappuccino framework.


f
flaalf

Is an MVC design pattern on the client side, believe me.. It's gonna save you tons of code, not to mention a more clean and clear code, a more easy to maintain code. Could be a little tricky at first, but believe me it's a great library.


R
Rahbee Alvee

So many good answers already. Backbone js helps to keep the code organised. Changing the model/collection takes care of the view rendering automaticallty which reduces lot of development overhead.

Even though it provides maximum flexibility for development, developers should be careful to destroy the models and remove the views properly. Otherwise there may be memory leak in the application.


s
superluminary

A web application involving lot of user interaction with many AJAX requests, which needs to be changed from time to time, and which runs in real time (such as Facebook or StackOverflow) ought to use an MVC framework such as Backbone.js. It's the best way to build good code.

If the application is only small though, then Backbone.js is overkill, especially for first time users.

Backbone gives you client side MVC, and all the advantages implied by this.


"must" use backbone? I can't see stackoverflow or facebook, your two examples, using backbone or underscore at all. Do you have a reference for that claim?
There are of course many other MV* libraries, Backbone being one of them. Generally though, MVC helps to keep things neat and tidy when developing larger pieces of code.