-1

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

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

3 Answers3

1

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
1
  1. path is not a special property on any of Backbone's classes
  2. 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;
kalley
  • 18,072
  • 2
  • 39
  • 36
0

Maybe you can write this code:

console.log(this.path+this.url)
Mario Araque
  • 4,562
  • 3
  • 15
  • 25
  • I can write like that, but while i fetch the data, it should fetch from full path right..? (this is not just consoling, i need to fetch the data using my base url) – 3gwebtrain Aug 14 '13 at 06:34
  • Yes, of course. I think its an external api, so you can use this thing- – Mario Araque Aug 14 '13 at 07:23