In my base collection i have the base path, from the base path i am extending further urls.. but while i console the url in the extended collection i am not getting the full path of the url..
instead just i am getting the url - what the extended collection have.. why i am getting like so, and what should be the proper approach?
here is my try :
BaseCollection = Backbone.Collection.extend({
path: 'http://path/to/api'
});
TeachersCollection = BaseCollection.extend({
url:"xyz/abc",
initialize:function(){
console.log(this.url);//xyz/abc - why i am getting like this instead of full path?
//full url should be 'http://path/to/api/xyz/abc' - how can i get like this..?
}
});
var x = new TeachersCollection;
live demo
path
is not a special property on any of Backbone's classes
- Models can have
urlRoot
, but there's no such thing for collections
Here's an approach that should work for you:
TeachersCollection = BaseCollection.extend({
url:function() {
return this.path + "/xyz/abc"
},
initialize:function(){
// this.url = _.result(this, 'url');
console.log(_.result(this, 'url'));
}
});
You may actually want to think about changing the constructor on your base collection, like this if you're going to be extending it a lot:
BaseCollection = Backbone.Collection.extend({
constructor: function() {
this.url = 'http://path/to/api' + this.url;
Backbone.Collection.prototype.constructor.apply(this, arguments);
}
});
TeachersCollection = BaseCollection.extend({
url: "/xyz/abc",
initialize:function(){
console.log(this.url);//xyz/abc
//full url should be 'http://path/to/api/xyz/abc'
}
});
var x = new TeachersCollection;
The easiest solution would be to use a function for url
, then you could do things like this:
TeachersCollection = BaseCollection.extend({
url: function() {
return this.path + '/xyz/abc';
},
//...
The problem with trying to use just a string for url
in such cases is getting the right this
so that you can look up the path
. You could go through BaseCollection.prototype
:
TeachersCollection = BaseCollection.extend({
url: BaseCollection.prototype.path + '/xyz/abc',
//...
but that's pretty cumbersome and noisy, I don't think saving the overhead of a function call is worth the hassle.
Maybe you can write this code:
console.log(this.path+this.url)