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?..
I don’t think you want to use a
Backbone.Routerto 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.Routercannot 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
hashchangeorpopstateevents (depending on if you are usingpushState). Since AJAX calls do no interact with the URL they pretty much totally bypass this system.