我正在研究我在codepen上找到的一个例子。该示例是关于创建后退按钮功能。我遇到的问题是当页面加载App.Router时不知道goto函数它说它是Uncaught TypeError:this.goto不是函数。我已经多次尝试解决这个问题,但我似乎无法让它完全运作。该示例位于codepen,我的工作示例为here
我的问题是路由器不知道我放在那里的goto功能。
非常感谢您的帮助
代码:
<!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>
答案 0 :(得分:1)
home
函数正在使用箭头函数来绑定this
的上下文。因此,window
对象可能是绑定的(而不是路由器),并且goto
不存在。将其更改为正常功能可以修复它。
home: function(query) {
console.log('home');
let view = new App.Views.Home();
this.goto(view); // doesn't work
}