Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Backbone Collection without a data source (no url)

First time posting here... looking forward to see how it all works, but have really appreciated reading other's questions & answers.

I am using backbone for a small app and have found it helpful to use a collection to store some information that is only required during the current session. (I have a number of collections and all the others connect to my API to store/retrieve data).

I read here (in backbone.js can a Model be without any url?) that it is possible, and even good to use a collection without providing a url.

Now I would like to add a row of data to the collection... simple:

myCollection.create(data);

but of course that now throws an error:

Uncaught Error: A "url" property or function must be specified

Is there any way to use a Backbone collection, be able to add new rows of data (models) to it, but not sync to any sort of data source. Or can you suggest another solution.

I guess I could just use an object to hold the data, but I was enjoying the consistency and functionality.

I am using Backbone.Marionette if that has any impact.

Thanks in advance.

like image 314
ozpritcha Avatar asked Aug 20 '13 22:08

ozpritcha


1 Answers

One thing you could do is override the Backbone.Model methods that communicate with the server, i.e. sync, fetch, and save... for example:

var App = {
    Models: {},
    Collections: {}
};

App.Models.NoUrlModel = Backbone.Model.extend({});
App.Models.NoUrlModel.prototype.sync = function() { return null; };
App.Models.NoUrlModel.prototype.fetch = function() { return null; };
App.Models.NoUrlModel.prototype.save = function() { return null; };

App.Collections.NoUrlModels = Backbone.Collection.extend({
    model: App.Models.NoUrlModel,
    initialize: function(){}
});

var noUrlModels = new App.Collections.NoUrlModels();
noUrlModels.create({'foo': 'bar'});  // no error
// noUrlModels.models[0].attributes == {'foo': 'bar'};

See Demo

like image 174
mVChr Avatar answered Oct 10 '22 01:10

mVChr