A model's urlRoot can now be a function allowing definition at runtime.

This commit is contained in:
=
2011-12-22 15:23:12 -10:00
parent 04cb79a528
commit b4e650b98f
2 changed files with 13 additions and 0 deletions

View File

@@ -293,6 +293,7 @@
// that will be called.
url : function() {
var base = getValue(this.collection, 'url') || this.urlRoot || urlError();
if (typeof(base) == 'function') base = base.call(this); // allow urlRoot to be determined at runtime
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
},

View File

@@ -87,6 +87,18 @@ $(document).ready(function() {
equals(model.url(), '/collection/%2B1%2B');
});
test("Model: url when using urlRoot as a function to determine urlRoot at runtime", function() {
var Model = Backbone.Model.extend({
urlRoot: function() { return '/nested/' + this.get('parent_id') + '/collection'}
// looks better in coffeescript: urlRoot: => "/nested/#{@get('parent_id')}/collection"
});
var model = new Model({parent_id: 1});
equals(model.url(), '/nested/1/collection');
model.set({id: 2});
equals(model.url(), '/nested/1/collection/2');
});
test("Model: clone", function() {
attrs = { 'foo': 1, 'bar': 2, 'baz': 3};
a = new Backbone.Model(attrs);