Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Difference between Backbone. Asked 10 years, 3 months ago. Active 10 years, 3 months ago. Viewed 2k times. Here is a description from backbone's website Backbone supplies structure to JavaScript-heavy applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing application over a RESTful JSON interface.
Doesn't jQuery do event binding, etc nicely already? At that point, you're looking at SPA territory and opening a new world of options and opportunities. Moving beyond an introduction to SPAs, though, Backbone. For example, Backbone. This isn't difficult to do, but it requires writing your own code or using another plug-in to handle it. Additionally, Backbone.
The render function for a Backbone. View is a prime example of this. You'll end up writing the same render method over and over and over again, if you're not careful. The problems of boilerplate and missing features are both a blessing and a curse. This allows you the freedom to use Backbone. But it does require that you write more code than some other frameworks.
Fortunately, the Backbone. There are dozens, if not hundreds, of plug-ins and add-ons for Backbone. There are a number of amazing resources out there for learning more about Backbone. Here are some of my favorites and recommended resources. Addy Osmani has written a book discussing the fundamentals of Backbone, with a collaborative approach through the use of Github and community contributions.
It is a comprehensive introduction to Backbone. It includes the core of everything you need to know, to get up and running, and move beyond simple applications like I've shown in this article. If you're not familiar with Addy's work in the JavaScript world, you need to be.
Thomas Davis has collected a wealth of knowledge in small installments through his Backbone. He has taken community input and information, and put it together in to a free e-book. It covers nearly every aspect of Backbone. My e-book on how-and more importantly, why-to build proper abstractions and add-ons for Backbone. This book will teach you the how and why of building plug-ins for Backbone.
It provides first hand lessons learned, best practices, and patterns for creating flexible add-ons and framework components. And it's all based on real-world experience-both success and failure-from working with Backbone. Along the way, he shows a number of common pitfalls and problems, and how to work through them.
I also make an appearance at the end of this series, introducing my MarionetteJS application framework. Brian Mann has a series of Backbone.
He has a number of free episodes and paid episodes, covering everything from the history of SPAs, to building scalable systems, and more. My screencast series on learning Backbone. The version of Backbone. If you're a visual learner and want to follow along with a step-by-step instruction set, then this is for you. One of the best categories of contributions from the Backbone.
There are a number of them out there, adding features and functionality for building larger and scalable application frameworks. These are the most popular, and I highly recommend looking at them if you plan on using Backbone. Formerly known as Backbone. Marionette, MarionetteJS is a composite application architecture for Backbone.
It provides a layer of specialized View abstractions ItemView, CollectionView, CompositeView the ability to nest views inside of each other with a Layout, an Application bootstrapper, a simple module system, and much more. LayoutManager is a logical foundation for assembling layouts and views within Backbone. Tim Branyen-a core contributor to the Backbone. It works both in browsers and in NodeJS on the server side, providing a lot of flexibility in where it is used.
It does this through the use of Coffeescript in its implementation, but can still be used with JavaScript. Chaplin's controllers and router management are worth looking at, even if you're using another application framework. Thorax started life in Wal-Mart labs, supporting their mobile effort. The tight integration with Handlebars for template rendering provides a unique flavor of building Backbone. Aura is a decoupled, event-driven architecture on top of Backbone.
Aura takes the approach of widget based development, and application composition with those widgets. It incorporates a lot of JavaScript community knowledge, and scalability concerns from years of experience with large scale JavaScript systems.
There are hundreds of other plug-ins available, covering everything from nested model structures, to specific server API usage. For a more complete listing of what the Backbone. My Subscriber Account Advertise Write. Training Home State of. Staffing Home Looking for Staff? Looking for Work? Contact Us. Download File. Dark Kimbie. Published in:. What is Backbone. Models encapsulate the data and associated behavior of data within an application.
Collection: A collection of models. Collections allow groups of related models to be held together and managed as a whole. Common collection features such as adding and removing, iteration, filtering are provided. View: A generalized collection of methods and the configuration for managing and manipulating the DOM, and for displaying data from Models and Collections. Events: A minimal yet robust implementation of the observer design pattern for JavaScript objects.
Events glue Backbone. Every object in Backbone. Routers and the History object allow an application state to be bookmarked or linked, reloading the page to exactly the place where it was left. Building a Contact List Dozens of application types require the storage and retrieval of contact information for other people, such as a CRM system, a time tracking app, accounting, or any of a number of other things. A simple contact list only needs a handful of features: List of contacts Add a contact Edit a contact Delete a contact Contact data It also needs data for to go with these features, including: Name Photo URL Email address Phone Number Notes A simple contact list used in learning the basics of Backbone.
Figure 1: This is the add contact form. Figure 2: This is the sample contact list. From jQuery to Backbone. Taking a migration approach to Backbone. Setting up Backbone Backbone. View and the Add Form Backbone. Rendering the addform Input Fields The most common function to add to a Backbone. Viewing the View Having a view definition is great, but it doesn't do much good until it's instantiated, rendered, and placed in to the DOM where users can see the content and interact with it.
Figure 3: TThe Add form has been rendered by the Backbone. View instance. DOM Events and Backbone. View To get the form data back to your server, from the form that the View rendered, you need to do three things: Handle the save button click.
Get the data from the form inputs in a manner that is easy to send to the server. Send it to the server and handle any response needed. Handling the Button Click Event The first step is to get the data from the form input, which is handled with the declarative events in the Backbone. View solves this problem with one very small addition to the selector syntax: this.
Saving Data with Backbone. Save the New Contact Back in the add form's saveClicked method, create a new instance of a Contact model. A List of Things with Backbone. Calling collection. If a model in the list isn't yet in the collection it will be added; if the model is already in the collection its attributes will be merged; and if the collection contains any models that aren't present in the list, they'll be removed. All of the appropriate "add" , "remove" , and "change" events are fired as this happens.
Returns the touched models in the collection. Useful if your collection is sorted, and if your collection isn't sorted, at will still retrieve models in insertion order.
When passed a negative index, it will retrieve the model from the back of the collection. Takes the same options as add. Takes the same options as remove. If you define a comparator, it will be used to sort the collection any time a model is added.
A comparator can be defined as a sortBy pass a function that takes a single argument , as a sort pass a comparator function that expects two arguments , or as a string indicating the attribute to sort by.
Note that Backbone depends on the arity of your comparator function to determine between the two styles, so be careful if your comparator function is bound.
Note how even though all of the chapters in this example are added backwards, they come out in the proper order:. Collections with a comparator will not automatically re-sort if you later change model attributes, so you may wish to call sort after changing model attributes that would affect the order.
Note that a collection with a comparator will sort itself automatically whenever a model is added. Calling sort triggers a "sort" event on the collection.
Equivalent to calling map and returning a single attribute from the iterator. Useful for simple cases of filter. If no model matches returns undefined. Models within the collection will use url to construct URLs of their own. The function is passed the raw response object, and should return the array of model attributes to be added to the collection.
The options hash takes success and error callbacks which will both be passed collection, response, options as arguments. Delegates to Backbone. The server handler for fetch requests should return a JSON array of models.
The behavior of fetch can be customized by using the available set options. For example, to fetch a collection, getting an "add" event for every new model, and a "change" event for every changed existing model, without removing anything: collection. Note that fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped in to place.
Equivalent to instantiating a model with a hash of attributes, saving the model to the server, and adding the model to the set after being successfully created. Returns the new model. If client-side validation failed, the model will be unsaved, with validation errors.
In order for this to work, you should set the model property of the collection. The create method can accept either an attributes hash and options to be passed down during model instantiation or an existing, unsaved model object.
Creating a model will cause an immediate "add" event to be triggered on the collection, a "request" event as the new model is sent to the server, as well as a "sync" event, once the server has responded with the successful creation of the model.
Collection and any collections which extend it. This can be used to add generic methods e. Web applications often provide linkable, bookmarkable, shareable URLs for important locations in the app.
Router provides methods for routing client-side pages, and connecting them to actions and events. For browsers which don't yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL.
During page load, after your application has finished creating all of its routers, be sure to call Backbone. Define action functions that are triggered when certain URL fragments are matched, and provide a routes hash that pairs routes to actions.
Note that you'll want to avoid using a leading slash in your route definitions:. Trailing slashes are treated as part of the URL, and correctly treated as a unique route when accessed. When the visitor presses the back button, or enters a URL, and a particular route is matched, the name of the action will be fired as an event , so that other objects can listen to the router, and be notified.
Router [options] For use with routers as ES classes. If you define a preinitialize method, it will be invoked when the Router is first created and before any instantiation logic is run for the Router. All options will also be passed to your initialize function, if defined. Each matching capture from the route or regular expression will be passed as an argument to the callback. The name argument will be triggered as a "route:name" event whenever the route is matched.
If the callback argument is omitted router[name] will be used instead. Routes added later may override previously declared routes. If you also wish to call the route function, set the trigger option to true. To update the URL without creating an entry in the browser's history, set the replace option to true.
Return false from execute to cancel the current transition. Override it to perform custom parsing or wrapping of your routes, for example, to parse query strings before handing them to your route callback, like so:.
History serves as a global router per frame to handle hashchange events or pushState , match the appropriate route, and trigger callbacks. You shouldn't ever have to create one of these yourself since Backbone. Older browsers that don't support pushState will continue to use hash-based URL fragments, and if a hash URL is visited by a pushState -capable browser, it will be transparently upgraded to the true URL.
Note that using real URLs requires your web server to be able to correctly render those pages, so back-end changes are required as well. For full search-engine crawlability, it's best to have the server generate the complete HTML for the page Subsequent calls to Backbone. When called, if a route succeeds with a match for the current URL, Backbone. If no defined route matches the current URL, it returns false.
If the server has already rendered the entire page, and you don't want the initial route to trigger when starting History, pass silent: true. By default, it uses jQuery. With the default implementation, when Backbone. When returning a JSON response, send down the attributes of the model that have been changed by the server, and need to be updated on the client.
When responding to a "read" request from a collection Collection fetch , send down an array of model attribute objects. Whenever a model or collection begins a sync with the server, a "request" event is emitted. If the request completes successfully you'll get a "sync" event, and an "error" event if not. The sync function may be overridden globally as Backbone.
As an example, a Rails 4 handler responding to an "update" call from Backbone might look like this:. One more tip for integrating Rails versions prior to 3. Backbone views are almost more convention than they are code — they don't determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library.
The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. Instead of digging into a JSON object, looking up an element in the DOM, and updating the HTML by hand, you can bind your view's render function to the model's "change" event — and now everywhere that model data is displayed in the UI, it is always immediately up to date.
You'll want to override the render function, specify your declarative events , and perhaps the tagName , className , or id of the View's root element. Properties like tagName , id , className , el , and events may also be defined as a function, if you want to wait to define them until runtime. If you define a preinitialize method, it will be invoked when the view is first created, before any instantiation logic is run. If the view defines an initialize function, it will be called when the view is first created.
In this fashion, views can be rendered at any time, and inserted into the DOM all at once, in order to get high-performance UI rendering with as few reflows and repaints as possible. If none are set, this. An el reference may also be passed in to the view's constructor.
A handy reference instead of re-wrapping the DOM element all the time. If you use this scoped jQuery function, you don't have to use model ids as part of your query to pull out specific elements in a list, and can rely much more on HTML class attributes.
It's equivalent to running: view. In this way, when rendering your view, you have convenient access to instance data. For example, using Underscore templates:. Override this function with your code that renders the view template from model data, and updates this. A good convention is to return this at the end of render to enable chained calls.
Backbone is agnostic with respect to your preferred method of HTML templating. Your render function could even munge together an HTML string, or use document. However, we suggest choosing a nice JavaScript templating library.
Because Underscore. Backbone will automatically attach the event listeners at instantiation time, right before invoking initialize. If an events hash is not passed directly, uses this. The callback may be either the name of a method on the view, or a direct function body.
Omitting the selector causes the event to be bound to the view's root element this. By default, delegateEvents is called within the View's constructor for you, so if you have a simple events hash, all of your DOM events will always already be connected, and you will never have to call this function yourself.
The events property may also be defined as a function that returns an events hash, to make it easier to programmatically define your events, as well as inherit them from parent views.
Using delegateEvents provides a number of advantages over manually using jQuery to bind events to child elements during render.
All attached callbacks are bound to the view before being handed off to jQuery, so when the callbacks are invoked, this continues to refer to the view object. When delegateEvents is run again, perhaps with a different events hash, all callbacks are removed and delegated afresh — useful for views which need to behave differently when in different modes.
A single-event version of delegateEvents is available as delegate. In fact, delegateEvents is simply a multi-event wrapper around delegate. A counterpart to undelegateEvents is available as undelegate. Useful if you want to disable or remove a view from the DOM temporarily. You can use the return value of Backbone.
Useful for embedding Backbone on third-party websites, where you don't want to clobber the existing Backbone. Why use Backbone, not [other framework X]? If your eye hasn't already been caught by the adaptability and elan on display in the above list of examples , we can get more specific: Backbone. In fact, Backbone.
For example References between Models and Views can be handled several ways. Some people like to have direct pointers, where views correspond with models model. Others prefer to have intermediate "controller" objects that orchestrate the creation and organization of views into a hierarchy.
Others still prefer the evented approach, and always fire events instead of calling methods directly. Bolsters integration with diverse systems, tools, and IDEs. Bolsters integration with diverse systems and web applications because it is lightweight to utilize. It was moreover authorized beneath MIT and kept up by Google.
It is licensed under MIT. Skip to content. Change Language. Related Articles. Table of Contents. Save Article. Improve Article. Like Article. Last Updated : 09 Nov, Recommended Articles.
Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment?
0コメント