"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application
Uncaught TypeError: undefined is not a function example_app.js:7
This error message tells the whole story. On this line, you are trying to execute a function. However, whatever is being executed is not a function! Instead, it's undefined
.
So what's on example_app.js
line 7? Looks like this:
var tasks = new ExampleApp.Collections.Tasks(data.tasks);
There is only one function being run on that line. We found the problem! ExampleApp.Collections.Tasks
is undefined
.
So lets look at where that is declared:
var Tasks = Backbone.Collection.extend({
model: Task,
url: '/tasks'
});
If that's all the code for this collection, then the root cause is right here. You assign the constructor to global variable, called Tasks
. But you never add it to the ExampleApp.Collections
object, a place you later expect it to be.
Change that to this, and I bet you'd be good.
ExampleApp.Collections.Tasks = Backbone.Collection.extend({
model: Task,
url: '/tasks'
});
See how important the proper names and line numbers are in figuring this out? Never ever regard errors as binary (it works or it doesn't). Instead read the error, in most cases the error message itself gives you the critical clues you need to trace through to find the real issue.
In Javascript, when you execute a function, it's evaluated like:
expression.that('returns').aFunctionObject(); // js
execute -> expression.that('returns').aFunctionObject // what the JS engine does
That expression can be complex. So when you see undefined is not a function
it means that expression did not return a function object. So you have to figure out why what you are trying to execute isn't a function.
And in this case, it was because you didn't put something where you thought you did.