Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js - Model URL vs Collection URL

Ahoy everyone!

Good day! I'm starting to adapt the Backbone.js framework and I'm having a slippery grasp on how the Model's URL:

   var TodoItem = Backbone.Model.extend({
     urlRoot: 'http://localhost:3354/api/todo/GetAllTodo' // this guy right here
   }

affects the Collection's URL - once the said model is used in collection:

 var TodoList = Backbone.Collection.extend({
                model: TodoItem,
                url: 'http://localhost:3354/api/todo/DosomethingElse' //Conflict of URL?
        }

Lastly, when I try the model.fetch(), the service returns a JSON representation of the data via [{}] format, this makes my model have an object property which houses the actual json data returned - this is a problem - as models are intended for a single record and not an array[] of data.

Thanks for your time and I really appreciate your help on this.

like image 829
KevinIsNowOnline Avatar asked Dec 17 '25 17:12

KevinIsNowOnline


1 Answers

If you check Backbone source code for Model.url , you'll see that the url base for a model is built by

var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url');

which means your TodoItem.urlRoot takes precedences over TodoList.url when you do a model.fetch()

You can use parse to extract the desired format:

var TodoItem = Backbone.Model.extend({
    urlRoot: 'http://localhost:3354/api/todo/GetAllTodo',
    parse: function(data) {
        return data[0];
    }
}
like image 169
nikoshr Avatar answered Dec 19 '25 17:12

nikoshr