PaulUithol/Backbone-relational — Issue #73: how does url function work?
Author: meecect
Created: 2012-02-03 01:49:26+00:00
State: open

I'm reading the source of backbone and backbone-relational trying to get a better handle on how the lib works. I am currently stumbling on a particular issue that I don't quite understand. I want to figure this out though, as I would like to write my own Backbone.sync function.

In backbone-relational, it seems to rely on setting the url on a collection to something like:

```javascript

AnimalCollection = Backbone.Collection.extend({
model: Animal,

url: function( models ) {
return '/animal/' + ( models ? 'set/' + _.pluck( models, 'id' ).join(';') + '/' : '' );
}
});

```
In these collections url is getting a list of models and is constructing a URL with all the model id's 'pluck'ed out. Seem straightforward.

But looking through the backbone source, i don't see how this url function works if it needs models passed to it like that.

In backbone in the sync function, which backbone-relational does _not_ override, it grabs the url parameter like this:

```javascript
// Ensure that we have a URL.
if (!options.url) {
params.url = getValue(model, 'url') || urlError();
}
```

getValue is a helper function:

```javascript

var getValue = function(object, prop) {
if (!(object && object[prop])) return null;
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
};

```
so, essentially getValue is checking to see if url is an object or a function, and if it is a function, it executes it like models.url(). In the typical case of backbone-relational, this would essentially be some_collection.url();

So how does Backbone-relational work then? I mean, I know it does work, but how, since it seems to rely the url function being called with an argument of a collection, or at least an array of models, I guess.

Any ideas as to what I am missing here?