Reputation: 1662
I am building a simple Backbone application. The 'users' collection looks like this:
//users collection module
module.exports = Backbone.Collection.extend({
url: '/api/users',
model: UserModel,
initialize: function() {
this.fetch();
}
});
The app.js file looks like this:
var UserCollection = require('./collections/users.js');
(function() {
var users = new UserCollection();
users.sync();
})();
All bundled with browserify. However, when it executes in the client the fetch() method returns models from the server successfully, but the sync() method yields an error:
Uncaught Error: A "url" property or function must be specified
Does anyone know an obvious reason why fetch() might work but not sync() for the same collection instance and url property?
Upvotes: 3
Views: 501
Reputation: 1662
OK, partially solved. Sorry for posting what has turned out to be a very context-specific answer, but after hours of debugging I was getting frustrated.
One problem was that the API route was refusing the id
and _id
keys from the json being sent as data with the put request for model.sync() (which is called by collection.sync()). Changing the route handler solved the problem
Basically the issue here was that model.save()'s PUT request was getting a 400 error response, but Backbone's verbose error was reporting instead that the url property itself didn't exist.
EDIT
All that said, model.save() and collection.fetch() work, but collection.sync() and model.sync() still don't. Anyone have any ideas?
Upvotes: 1
Reputation: 10050
http://backbonejs.org/#Model-sync
syncmodel.sync(method, model, [options]) Uses Backbone.sync to persist the state of a model to the server. Can be overridden for custom behavior.
fetchmodel.fetch([options]) Resets the model's state from the server by delegating to Backbone.sync. Returns a jqXHR. Useful if the model has never been populated with data, or if you'd like to ensure that you have the latest server state. A "change" event will be triggered if the server's state differs from the current attributes. Accepts success and error callbacks in the options hash, which are both passed (model, response, options) as arguments.
// Poll every 10 seconds to keep the channel model up-to-date.
setInterval(function() {
channel.fetch();
}, 10000);
Upvotes: 2