Skip to content

zefhemel/ampersand-rest-collection

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ampersand-rest-collection

Extends ampersand-collection with REST and Underscore mixins.

This makes ampersand-collection work and act a lot like Backbone.Collection, if youre planning on hitting a REST-ful API this is probably what you want to use.

browser support

testling badge

Part of the Ampersand.js toolkit for building clientside applications.

Install

npm install ampersand-rest-collection

example

Define a collection

var Collection = require(ampersand-rest-collection);
var Model = require(some-model);


module.exports = Collection.extend({
    model: Model,
    url: /models
});

Using it:

var Collection = require(./path-to-your-collection-module);


var c = new Collection();

// call RESTful methods
c.fetch();

// also has underscore mixins
c.each(function (model) {
    console.log(model:, model);
});

API Reference

The ampersand-rest-collection is simply an ampersand-collection extended with two mixins: ampersand-collection-rest-mixin and ampersand-collection-underscore-mixin.

var Collection = require(ampersand-collection);
var underscoreMixin = require(ampersand-collection-underscore-mixin);
var restMixins = require(ampersand-collection-rest-mixin);

module.exports = Collection.extend(underscoreMixin, restMixins);

ajaxConfig AmpersandRestCollection.extend({ ajaxConfig: function () { ... } })

ampersand-sync will call ajaxConfig on your collection before it makes the request to the server, passing it the request parameters. When extending your own collection, set an ajaxConfig function to modify the request before it goes to the server. Useful for setting headers/CORS options etc.

The function will be called with params as the first argument, which is the object which will be passed to the underling jQuery.ajax call by ampersand-sync.

var MyCollection = AmpersandRestCollection.extend({
    url: 'http://otherdomain.example.com/stuff',

    ajaxConfig: function (params) {
        //Enable CORS requests
        params.crossDomain = true;

        //Send cookies cross domain for auth
        params.xhrFields = params.xhrFields || {};
        params.xhrFields.withCredentials = true;

        return params;
    }
});

var collection = new MyCollection()
collection.fetch();

fetch collection.fetch([options])

Fetch the default set of models for the collection from the server, setting them on the collection when they arrive. If the collection already contains data, by default, the operation of set will add new models from the server, merge the attributes of existing ones, and remove any which aren't in the response. This behaviour can be modified with the reset, add, remove, merge options.

Options:

  • success {Function} [optional] - callback to be called if the request was successful, will be passed (collection, response, options) as arguments.
  • error {Function} [optional] - callback to be called if the request was not successful, will be passed (collection, response, options) as arguments.
  • reset {Boolean} [optional] - call reset instead of set with the models returned from the server, defaults to false.
  • add {Boolean} [optional] - (assuming reset is false), {add: false} prevents the call to set from adding new models retrieved from the server that aren't in the local collection. Defaults to false
  • remove {Boolean} [optional] - (assuming reset is false), {remove: false} prevents the call to set from removing models that are in the local collection but aren't returned by the server. Defaults to false
  • merge {Boolean} [optional] - (assuming reset is false), {merge: false} prevents the call to set from updating models in the local collection which have changed on the server. Defaults to false

You can also pass any options that jQuery.ajax expects to modify the query. For example: to fetch a specific page of a paginated collection: collection.fetch({ data: { page: 3 } })

getOrFetch collection.getOrFetch('id', [options], callback)

Convenience method for gets a model from the server or from the collection if it's already has a model with that id.

By default it will only fetch and add the model with the ID you pass in.

collection.getOrFetch('42', function (err, model) {
    if (err) {
        console.log('handle');
    } else {
        // `model` here is a fully inflated model
        // It gets added to the collection automatically.
        // If the collection was empty before, it's got 1
        // now.
    }
});

If you pass {all: true} it will fetch the entire collection (by calling its fetch method) and then do a get to attempt to pull out the model by the id you specified.

collection.getOrFetch('42', {all: true}, function (err, model) {
    if (err) {
        console.log('handle');
    } else {
        // `model` here is a fully inflated model
        // It gets added to the collection automatically. 
    }
});

fetchById collection.fetchById('id', callback)

Fetches and adds a model by id to the collection. This is what getOrFetch uses if it doesn't have a model already.

collection.fetchById('42', function (err, model) {
    // returns inflated, added model with a `null` error
    // or an error object.
});

create collection.create(model, [options])

Convenience to create a new instance of a model within a collection. 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 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. Pass {wait: true} if you'd like to wait for the server before adding the new model to the collection.

var Library = AmpersandRestCollection.extend({
  model: Book
});

var library = new Library;

var othello = library.create({
  title: "Othello",
  author: "William Shakespeare"
});

sync model.sync(method, collection, [options])

Simple delegation to ampersand-sync to persist the collection to the server. Can be overridden for custom behaviour.

underscore methods (42)

The ampersand-collection-underscore-mixin proxies the collection methods in underscore onto the underlying models array for the collection. For example:

books.each(function(book) {
  book.publish();
});

var titles = books.map(function(book) {
  return book.get("title");
});

var publishedBooks = books.filter(function(book) {
  return book.get("published") === true;
});

var alphabetical = books.sortBy(function(book) {
  return book.author.get("name").toLowerCase();
});

The full list of proxied methods is:

credits

If you like this follow @HenrikJoreteg on twitter.

license

MIT

About

ampersand-collection with REST and Underscore mixins for easy use with REST APIs.

Resources

Stars

Watchers

Forks

Packages

No packages published