我将我正在运行的Backbone.js应用程序拆分为模型,视图和路由器的单独文件。
启动我的路由器:
window.App = Backbone.View.extend({
initialize: function() {
require(["routers/my-router"], function (MyRouter) {
var myRouter = new myRouter();
Backbone.history.start();
});
}
});
在我的路由器文件routers/my-router.js
中,我正在收听模型的更改事件:
define(function (require) {
"use strict";
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone');
return Backbone.Router.extend({
initialize: function() {
var self = this;
require([],
function(){
var model = new Backbone.Model.extend({});
self.listenTo(model, 'change', self.callback);
model.trigger('change');
}
);
},
callback: function() {
console.log('callback reached!');
}
});
});
我因定义回调的不同方式而收到以下错误:
self.callback
:Uncaught TypeError: undefined is not a function
callback
:Uncaught ReferenceError: callback is not defined
this.callback
:Uncaught TypeError: Cannot read property 'onManualDestination' of undefined
这个问题是在Yurui的回答之后编辑的。
答案 0 :(得分:1)
要执行Router的初始化方法,您必须创建一个Router实例,然后使用Backbone.history.start(),如下所示:
//define router:
var Router = Backbone.Router.extend({});
//instantiate a router
new Router();
//start router!
Backbone.history.start();
在您的示例中,路由器未实例化,也未启动。 此外,不会触发模型更改。
这是我的工作范例:
//define a model.
var Model = Backbone.Model.extend({});
//define a router
var Router = Backbone.Router.extend({
initialize: function () {
var self = this;
setTimeout(function () {
var myModel = new Model({});
self.listenTo(myModel, 'change', self.callback);
//triggers change right away so you can see the callback output
myModel.trigger('change');
}, 1000);
},
callback: function () {
console.log('Callback reached!');
}
});
//instantiate the router!
new Router();
//here's when router.initialize() is called.
Backbone.history.start();
注意:我使用setTimeout
替换requirejs
的使用,但在此示例中不应影响任何内容。
jsfiddle:http://jsfiddle.net/4KLCZ/