I've been working through codeschool.com's tutorial on backbone.js And submitted:

var AppRouter = new Backbone.Router.extend({
  //code
});
$(function(){ AppRouter.start() });

and it gave the following error message:

TypeError: 'undefined' is not a function (evaluating 'AppRouter.start()') :28 :14

but adding a single parentheses solved the problem

var AppRouter = new (Backbone.Router.extend({
  //code
}));

I feel like it should have still worked before... What was happening when there was one less parentheses?

有帮助吗?

解决方案

It was using Backbone.Router.extend as the constructor (with the parentheses going as arguments to the constructor, not the result of the Backbone.Router.extend call (where the call to Backbone.Router.extend returns a function to be used as a constructor). For example, compare:

function Test()
{   return function () { this.a = 2; };
}

console.log(new Test()); // function () { this.a = 2; }
console.log(new (Test())); // { a: 2 }

其他提示

Answered another way, you need to be working with an instance of Backbone.Router, which you can first extend with your own router. Such as:

var AppRouter = Backbone.Router.extend({
    routes: {
        // code
    }
});

var router = new AppRouter();
Backbone.history.start();

The code in your example is evaluating the extend call first, then creating an instance with the return value. The end result is the same, but could be a bit misleading if you don't know the parentheses are causing the evaluation to take place.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top