如何在 backbone.js 事件委托中使用 "hashchange" 事件?
How to use "hashchange" event in backbone.js event delegates?
在我的 backbone.js 项目中,我需要一个仅在 window.location.hash
变化时触发的方法。我为我的问题找到了一些替代解决方案 here.
此外,我可以通过在我的 backbone 视图 initialize function
中创建一个事件来解决这个问题,如下所示
Backbone.View.extend({
initialize() {
$(window).on('hashchange',()=> {
console.log('yes hashchange events works')
});
}
但我寻求使用 backbone.js's
eventDelegates
或 listenTo
的解决方案
提前致谢
您可以对这个范围使用 Backbone.history
。
History serves as a global router (per frame) to handle hashchange
events or pushState, match the appropriate route, and trigger
callbacks. You shouldn't ever have to create one of these yourself
since Backbone.history already contains one.
因为会触发回调,所以可以监听hashchange
个事件:
Backbone.history.on("all", function (route, router) {
console.log(window.location.hash);
});
或
Backbone.history.on("route", function () {
console.log(window.location.hash);
});
试试这个来初始化函数:
window.addEventListener('hashchange', function {
var currentHash = location.hash;
console.log('currentHash', currentHash);
})
在我的 backbone.js 项目中,我需要一个仅在 window.location.hash
变化时触发的方法。我为我的问题找到了一些替代解决方案 here.
此外,我可以通过在我的 backbone 视图 initialize function
中创建一个事件来解决这个问题,如下所示
Backbone.View.extend({
initialize() {
$(window).on('hashchange',()=> {
console.log('yes hashchange events works')
});
}
但我寻求使用 backbone.js's
eventDelegates
或 listenTo
提前致谢
您可以对这个范围使用 Backbone.history
。
History serves as a global router (per frame) to handle hashchange events or pushState, match the appropriate route, and trigger callbacks. You shouldn't ever have to create one of these yourself since Backbone.history already contains one.
因为会触发回调,所以可以监听hashchange
个事件:
Backbone.history.on("all", function (route, router) {
console.log(window.location.hash);
});
或
Backbone.history.on("route", function () {
console.log(window.location.hash);
});
试试这个来初始化函数:
window.addEventListener('hashchange', function {
var currentHash = location.hash;
console.log('currentHash', currentHash);
})