我正在处理一个我在codepen上找到的例子。这个例子是关于创建后退按钮功能的。我遇到的问题是当页面加载应用程序时。路由器不知道后藤函数,它说它是未捕获的TypeError:后藤不是一个函数。我已经检查了这个例子很多次,试图解决这个问题,但是我似乎根本不能让它工作。这个例子是在codepen上,我的工作例子是here
我的问题是路由器不知道我在那里放的后藤函数。
你的帮助将不胜感激
密码:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>
<script type="text/javascript">
(function() {
window.App = {
Models: {},
Views: {},
Extensions: {},
Forms: {},
Controllers: {},
Router: null,
linkClicked: false,
routes: [],
backDetected : false,
previousFragment : null,
init: (route) => {
new App.Router();
this.instance = new App.Views.App();
Backbone.history.start();
}
}
App.Router = Backbone.Router.extend({
routes: {
'': 'home'
},
execute: function(callback, args) {
var self = this,
answer = $.Deferred(),
route = Backbone.history.getFragment();
if (route === '') {
route = 'home';
}
App.backDetected = false;
if (App.routes[App.routes.length - 2] === route && !App.linkClicked) {
App.backDetected = true;
App.routes.pop();
if (App.routes[App.routes.length - 1] === route) {
App.routes.pop();
}
}
if (App.routes[App.routes.length - 1] !== route) {
App.routes.push(route);
}
_.delay(function() {
// this is super hacky but need a delay as global event on links
// takes ages to execute
App.linkClicked = false;
}, 500);
answer.promise().then(function() {
App.dirty = false;
window.onbeforeunload = null;
if (callback) {
callback.apply(self, args);
} else {
console.log('no callback');
}
});
if (App.dirty) {
console.log('app is dirty');
window.onbeforeunload = (function(_this) {
})(this);
} else {
answer.resolve();
}
},
initialize: function(options) {
var self = this;
this.options = options || {};
},
goto: function(view, params) {
console.log('goto');
console.log(App.instance);
},
home: (query) => {
console.log('home');
let view = new App.Views.Home();
this.goto(view); // doesn't work
}
});
App.Extensions.View = Backbone.View.extend({
goto: function(view) {
console.log('showing view');
}
});
App.Views.App = App.Extensions.View.extend({
})
App.Views.Home = App.Extensions.View.extend({
});
})();
$(function() {
//new App.Router();
window.App.init();
});
</script>
<title></title>
</head>
<body>
</body>
</html>
1条答案
按热度按时间ssm49v7z1#
home
函数正在使用绑定this
上下文的箭头函数。因此,window
对象可能是被绑定的对象(而不是路由器),而goto
在该对象上不存在。将其更改为普通函数可以修复它。