1

I have a model and I am trying to fetch it using model.fetch();. The model's urlRoot set to the back-end of my application ("/backend/item"), but right now I don't have the back-end environment. So I decided to mock the results. I added a route inside my router:

"backend/item/:id": "data_getItem"

and a function:

data_getItem: function(id) {
  console.log("data_getItem: "+ id);
  return {
    animals: [
      {
        name: 'flying cat',
        type: 'none'
      }
    ]
  };
}

When running the application I can see ajax call to "http://127.0.0.1:8000/backend/item/1" but the console is empty and I get an error (the fetch function returns me to the error callback). Why is that? How can I mock the back-end?

EDIT Actually @rjz helped me with the things I want to do, but I really want to know if an ajax call can be catched by backbone router. My intuition tells me not because ajax call cannot execute backbone client code and therefore the router concept is not relevant. Am I right?..

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
Naor
  • 23,465
  • 48
  • 152
  • 268
  • You might read over http://stackoverflow.com/questions/5096549/how-to-override-backbone-sync – rjz Nov 11 '12 at 23:29
  • @rjz: Actually this helped me but I really want to know if an ajax call can get access to route. – Naor Nov 12 '12 at 00:32

1 Answers1

0

I don't think you want to use a Backbone.Router to catch your AJAX calls. If your goal is mocking out the backend of your project, you should use a testing framework to do this. A down and dirty way would be to use something like:

or if you want to do something more like unit testing I would look at Jasmine and its AJAX mocking library.

Update to answer your question:

The short answer is no, a Backbone.Router cannot intercept AJAX calls.

This is because the router works by listening to events that have to do with the URL. Specifically, the router is listening to the hashchange or popstate events (depending on if you are using pushState). Since AJAX calls do no interact with the URL they pretty much totally bypass this system.

Andrew Hubbs
  • 9,338
  • 9
  • 48
  • 71
  • Thanks, but I am asking about the possibility of ajax call to be catched by backbone router. I know this is not optimal or not the way to do it (and I am not going to use it) but I am just asking hypotheticalץ – Naor Nov 12 '12 at 09:09
  • Added changes to answer you question. Short answer: No it can't. – Andrew Hubbs Nov 15 '12 at 00:46