gpt4 book ai didi

javascript - 如何在触发功能之前停止 Backbone 路由事件?

转载 作者:行者123 更新时间:2023-11-30 12:34:11 26 4
gpt4 key购买 nike

我希望能够在“之前”函数中停止路由触发器。上面的功能运行良好。它正确调用“之前”方法。当调用“before”方法时,有什么合适的方法来停止路由吗?

更新:已解决!

(function () {
_.extend(Backbone.Router.prototype, Backbone.Events, {
route: function (route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, _.bind(function (fragment) {
var args = this._extractParameters(route, fragment);

if (_.isFunction(router.before)) {
if (router.before.apply(this, args) === false) return;
}
callback && callback.apply(this, args);
this.trigger.apply(this, ['route:' + name].concat(args));
if (_.isFunction(router.after)) {
router.after.apply(router, args);
}
Backbone.history.trigger('route', this, name, args);
}, this));
return this;
}
});
}).call(this);

这是路由代码:

var AppRouter = Backbone.Router.extend({
routes: {
'': 'home',
'help(/)': 'help', // about or /about/
'page(/:id)(/)' : 'page',
'*path' : 'notFound'
},
before: function () {
return false; // the magic
},
after: function () {
},
});

它是这样工作的。 return false 现在可以停止进程。完美的。该解决方案基于knpsck的解决方案。

最佳答案

beforeafter Hook - 是额外的功能。你可以这样实现它(Backbone 1.1.2)

Backbone.Router.prototype.route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);

if (_.isFunction(name)) {
callback = name;
name = '';
}

if (!callback) callback = this[name];

var router = this;

Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);

if (_.isFunction(router.before)) {
if (router.before.apply(this, args) === false) return;
}

router.execute(callback, args);

if (_.isFunction(router.after)) {
router.after.apply(router, args);
}

router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
Backbone.history.trigger('route', router, name, args);
});

return this;
}

关于javascript - 如何在触发功能之前停止 Backbone 路由事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26637191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com