Using a Backbone Collection without a data source (no url)
Asked Answered
M

1

8

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.

Mumford answered 20/8, 2013 at 22:53 Comment(0)
C
17

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

Codeine answered 21/8, 2013 at 0:56 Comment(2)
Very clear concise explanation. Thank you. I hadn't realised it was so easy to override methods like this!Mumford
Perhaps worth noting that you can also specify the sync, fetch and save methods in your model definition without referring to the prototype chain.Ona

© 2022 - 2024 — McMap. All rights reserved.