Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly set up the Backbone.js urlRoot method

I am having trouble understanding how urlRoot works in Backbone.js. I am attempting to fetch a task with a specific _id from a NodeJS/MongoDB backend.

What I'm not exactly clear on is how to pass the id attribute into the URI. I've been doing the following from Chrome dev tools:

var task = new App.Models.Task({ id: '51c09ae7d3b35d29d4dfdecd' });
task.fetch();

And I receive the following error:

GET http://localhost:3000/tasks/:_id 500 (Internal Server Error) 

How do I properly set this up?

Here's my Backbone code:

(function() {

  window.App = {
    Models: {},
    Views: {},
    Collections: {}
  };

  App.Models.Task = Backbone.Model.extend({
    defaults: {
      title: '',
      completed: false
    },

    idAttribute: "_id",

    urlRoot: '/tasks/:_id'
  });

})();
like image 851
Evan Emolo Avatar asked Jun 18 '13 19:06

Evan Emolo


People also ask

Why use Backbone js?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.

How does Backbone JS work?

Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.


1 Answers

Looking at http://backbonetutorials.com/what-is-a-model/ for guidance I would say you don't need to define the idAttribute and your urlRoot should just be "/tasks". Backbone should handle the rest.

Note: I haven't used Backbone myself yet but have been reading up on it.

like image 165
Nick Roth Avatar answered Sep 23 '22 15:09

Nick Roth