Backbone.js - base path not concat with subpaths

2019-09-20 16:42发布

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

3条回答
时光不老,我们不散
2楼-- · 2019-09-20 17:09

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.

查看更多
你好瞎i
3楼-- · 2019-09-20 17:15

Maybe you can write this code:

console.log(this.path+this.url)
查看更多
走好不送
4楼-- · 2019-09-20 17:29
  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;
查看更多
登录 后发表回答