man*_*nta 8 navigation highlighting backbone.js
我想突出显示当前的导航状态.就像哈希变换一样#home,我想以不同的方式设置'Home'菜单链接的样式,并且类似于其他链接.
当单击和其他链接时route:home,Backbone.js会触发单个事件,例如.......我看不到每个hashchange都会触发的任何常见事件.有了这个,我需要通过绑定到所有路由事件来编写状态突出显示逻辑,我认为这不是一个好的解决方案.route:some-other#home
所以,我已经Backbone.Router.route在我的路由器子类/对象中重写了,比如
// override backbone' Router.route method to publish
// common 'route_change' event for any hash change
route : function(route, name, callback) {
Backbone.history || (Backbone.history = new Backbone.History);
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
Backbone.history.route(route, _.bind(function(fragment) {
var args = this._extractParameters(route, fragment);
callback.apply(this, args);
this.trigger.apply(this, ['route:' + name].concat(args));
// ADDED BY: ManiKanta G
// name: route method
// fragment: route path
// args: any additional args
this.trigger.apply(this, ['route_change'].concat(name, fragment, args));
}, this));
}
Run Code Online (Sandbox Code Playgroud)
这将发布一个公共route_change事件,每hashchange和传递name,fragment以及其他args使用该余米强调所有在一个地方的状态.
我的问题是我是否必须覆盖这样的Backbone方法,或者我可以在这里使用任何构建机制.如果没有,我想在Backbone.js中看到类似的行为
编辑:示例程序
Router = Backbone.Router.extend({
routes : {
'': 'root',
'home': 'home',
'about':'about'
},
// app routing methods
root: function () { console.log('root route'); },
home: function () { console.log('home route'); },
about: function () { console.log('about route'); }
});
Router.bind('all', function () {
console.log('all route...');
});
router = new Router();
Run Code Online (Sandbox Code Playgroud)
并使用上述路由器导航:
router.navigate('home', true);
Run Code Online (Sandbox Code Playgroud)
输出: home route
更新上述计划无效的原因:
我们应该绑定all事件Router instance,而不是绑定Router自身 - 所以,更改Router.bind('all', ...为router.bind('all', ...)将使上述程序工作
在主干0.5.x中,您可以将all事件绑定到路由器实例,并且传递给您的处理程序的第一个参数将是路由
以下是jsfiddle的例子,转载于此:
var dummy = Backbone.Router.extend({
defaultPage: 'messages',
routes: {
'': 'index',
'index': 'index',
'mailbox': 'mailbox'
},
index: function() {
// code here
},
mailbox: function() {
// code here
}
});
var router = new dummy();
router.bind('all', function(route) {
document.write('triggered: ' + route + '<br/>');
});
router.navigate('index', true);
router.navigate('mailbox', true);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9409 次 |
| 最近记录: |