Backbone.js

repository·master·Indexed 12 days ago

https://github.com/jashkenas/backbone

A lightweight JavaScript library version 1.6.1 that provides structure to web applications using Models, Collections, Views, and Routers. It offers tools for data binding, RESTful JSON communication, and custom event management via Backbone.Events, as well as browser history management through Backbone.History.

Tokens
4.7K
Snippets
15
Records
17
Agent score
49%

What's inside Backbone

  1. Overview of Backbone core abstractions

    master

    Backbone provides structure to JavaScript-heavy applications through four primary abstractions:

    • Models: Handle data with key-value binding and custom events.
    • Collections: Provide a rich API of enumerable functions for managing sets of models.
    • Views: Manage the UI and provide declarative event handling.
    • RESTful JSON Interface: Connects the application data to existing backends via standard JSON interfaces.
  2. Use Backbone.Events to manage custom event channels

    master

    The Backbone.Events module can be mixed into any object to provide a custom event channel. You can bind callbacks to events using on, remove them with off, or trigger them with trigger.

    Key methods:

    • on(name, callback, context): Binds a callback to an event. Supports space-separated event names (e.g., 'change blur') and event maps (e.g., { 'change': callback }).
    • off(name, callback, context): Removes callbacks. If no arguments are provided, it removes all listeners for all events.
    • once(name, callback, context): Binds a callback that will only fire once.
    • trigger(name, *args): Fires all bound callbacks for the specified event name.
    • listenTo(obj, name, callback): An inversion-of-control version of on. The current object listens to an event on obj, allowing for easier cleanup using stopListening.
    • stopListening(obj, name, callback): Tells the current object to stop listening to specific events or all events on the target obj.
    var object = {};
    _.extend(object, Backbone.Events);
    object.on('expand', function() {
      alert('expanded');
    });
    object.trigger('expand');
  3. Iterate over a Backbone.Collection

    master

    Backbone.Collection implements the JavaScript Iterable protocol, allowing you to use for...of loops. It provides three ways to iterate via specialized iterator methods:

    • values(): Iterates over the models themselves.
    • keys(): Iterates over the model IDs.
    • entries(): Iterates over [id, model] tuples.

    These methods return a CollectionIterator which is itself iterable.

    // Using for...of with values()
    for (const model of collection.values()) {
      console.log(model.attributes);
    }
    
    // Using for...of with entries()
    for (const [id, model] of collection.entries()) {
      console.log(id, model.attributes);
    }
  4. Configure Backbone HTTP emulation

    master

    You can configure Backbone to support legacy HTTP servers by setting the following global flags:

    • Backbone.emulateHTTP: When true, Backbone will fake PATCH, PUT, and DELETE requests using the _method parameter and the X-Http-Method-Override header.
    • Backbone.emulateJSON: When true, Backbone will encode the model as application/x-www-form-urlencoded instead of application/json to support servers that cannot handle direct JSON requests.
    Backbone.emulateHTTP = true;
    Backbone.emulateJSON = true;
  5. Fetch data into a Backbone.Collection

    master

    The fetch method retrieves the default set of models for a collection from the server, resetting the collection when they arrive.

    • By default, it uses set to add models. If options.reset: true is passed, the response data is passed through the reset method instead.
    • It triggers a 'sync' event upon success.
    • It uses the collection's sync method to perform the request.

    Options:

    • parse: (boolean, default true) Whether to parse the response.
    • reset: (boolean) If true, uses reset instead of set on success.
    • success: A callback function invoked on success.
    collection.fetch({ 
      reset: true, 
      success: function(collection, response) {
        console.log('Fetched successfully', response);
      }
    });
  6. Create and manage Backbone.Collection

    master

    A Backbone.Collection is a collection of Backbone.Model instances (or raw objects). It maintains indexes of models for order and lookup by id.

    Core functionality:

    • add(models, options): Adds one or more models to the collection.
    • remove(models, options): Removes models from the collection.
    • set(models, options): Updates the collection by adding new models, removing those no longer present, and merging existing ones. This is the primary way to update a collection's contents.
    • reset(models, options): Replaces the entire collection with a new list of models. This is optimized for bulk operations.
    • push(model, options) / pop(options): Standard array-like operations for the end of the collection.
    • unshift(model, options): Adds a model to the beginning of the collection.
    • toJSON(options): Returns an array of the models' attributes.
    • comparator: If specified, the collection will maintain its models in sort order based on this function or attribute name.
    var MyCollection = Backbone.Collection.extend({
      model: MyModel,
      comparator: 'name'
    });
    
    var collection = new MyCollection([{ name: 'Zebra' }, { name: 'Apple' }]);
    // Collection will be sorted: Apple, Zebra
  7. Configure and use Backbone.View

    master

    A Backbone.View represents a logical chunk of UI. It manages a DOM element (this.el) and handles events via delegation.

    Core Lifecycle Methods:

    • preinitialize(options): Runs before any instantiation logic. Use this for setup that must happen before this.el is created.
    • initialize(options): The standard initialization method. Override this for your view's logic.
    • render(): The core method to populate this.el with HTML. Convention: Always return this to allow chaining.
    • remove(): Removes the view's element from the DOM and stops all event listeners.

    Event Delegation: Define an events hash to map DOM events to view methods:

    events: {
      'click .button': 'handleClick',
      'mousedown .title': function(e) { ... }
    }

    Key Properties:

    • this.el: The root DOM element of the view.
    • this.$el: The jQuery-wrapped version of this.el.
    • this.cid: A unique ID for the view instance.
    var MyView = Backbone.View.extend({
      el: '<div>',
      events: {
        'click .btn': 'onBtnClick'
      },
      initialize: function() {
        console.log('View initialized');
      },
      render: function() {
        this.$el.html('<button class="btn">Click Me</button>');
        return this;
      },
      onBtnClick: function() {
        alert('Button clicked!');
      }
    });
    
    const view = new MyView();
    view.render().$el.appendTo('body');
  8. Manage models in a Backbone.Collection

    master

    Backbone.Collection provides several methods to manipulate and query the set of models it contains:

    • get(obj): Retrieves a model by its ID, CID, the model object itself, or an attributes object.
    • has(obj): Returns true if the model is present in the collection.
    • at(index): Returns the model at the specified index (supports negative indices).
    • where(attrs, [first]): Returns models that match the provided attributes. If first is true, it returns only the first match.
    • findWhere(attrs): A shorthand for where(attrs, true) to return the first matching model.
    • pluck(attr): Returns an array of the values of a specific attribute from every model.
    • shift(options): Removes the first model from the collection.
    • slice(): Returns a sub-array of models using standard array slicing.
    • sort(options): Forces the collection to re-sort itself based on the comparator. Triggers a 'sort' event unless options.silent is true.
    // Example usage of collection methods
    const collection = new Backbone.Collection([model1, model2]);
    const model = collection.get({ id: 1 });
    const matches = collection.where({ status: 'active' });
    const names = collection.pluck('name');
    collection.sort();
  9. Extend Backbone classes using .extend()

    master

    All core Backbone classes (Model, Collection, View, Router, and History) include an .extend() method. This method is used to create subclasses with custom properties and methods.

    • protoProps: An object containing the prototype properties and methods for the subclass.
    • staticProps: An object containing static properties for the subclass.
    • constructor: If provided within protoProps, it will be used as the subclass constructor. Otherwise, the subclass will default to calling the parent constructor.
    var MyModel = Backbone.Model.extend({
      // Prototype properties
      defaults: { name: 'Unknown' },
      
      initialize: function() {
        console.log('Model initialized');
      },
    
      sayHello: function() {
        console.log('Hello, ' + this.get('name'));
      }
    }, {
      // Static properties
      VERSION: '1.0.0'
    });
  10. Create and manage Backbone.Model

    master

    A Backbone.Model represents a discrete chunk of data and related methods for transformation.

    Core functionality:

    • set(key, val, options): Updates model attributes and triggers 'change' events. Supports both set('key', 'value') and set({ key: 'value' }) syntax. Use {silent: true} to prevent triggering events.
    • get(attr): Returns the value of an attribute.
    • unset(attr, options): Removes an attribute from the model.
    • toJSON(options): Returns a copy of the model's attributes.
    • fetch(options): Retrieves the model from the server and merges the response into the model.
    • save(key, val, options): Syncs the model to the server. If wait: true is passed, it waits for the server response before updating local attributes.
    • destroy(options): Removes the model from the server.
    • isValid(options): Checks if the model is in a valid state based on the validate method.
    • parse(resp, options): A method to convert a server response into a hash of attributes. Override this to transform data before it is set on the model.
    var MyModel = Backbone.Model.extend({
      defaults: { name: 'Default Name' },
      validate: function(attrs) {
        if (!attrs.name) return 'Name is required';
      }
    });
    
    var model = new MyModel({ name: 'John' });
    model.set({ name: 'Jane' });
    model.save();
  11. Add routes to a Backbone.Router

    master

    When using a Backbone.Router, you can define routes that match URL fragments. The route method adds a handler to the router's internal list. Routes are tested against the current fragment using regex.

    • route(route, callback): Adds a route. route is typically a RegExp, and callback is the function executed when a match occurs.
    var MyRouter = Backbone.Router.extend({
      routes: {
        '': 'index',
        'about': 'about'
      },
      index: function() {
        console.log('Index page');
      },
      about: function() {
        console.log('About page');
      }
    });
    
    var router = new MyRouter();
    Backbone.history.start();
  12. Restore previous Backbone instance with noConflict()

    master

    If Backbone was previously assigned to the global Backbone variable, you can call Backbone.noConflict() to restore the previous value and return the current Backbone instance.

    var Backbone = require('backbone');
    var previousBackbone = window.Backbone;
    
    // ... use Backbone ...
    
    Backbone.noConflict();
    // window.Backbone is now restored to previousBackbone