我有两个选项卡的视图。单击选项卡时,我想:
- 显示选项卡
- 将哈希更改为
#view/tabName
#view/tab1
如果和之间的哈希值发生变化#view/tab2
,则不会触发路由,但视图会显示tab2。如果哈希值从#anotherView
变为#view/tabName
,则路由将触发,并使用初始选项卡tabName呈现视图。
总而言之,当哈希在具有相同前缀的哈希之间发生变化时#view
,视图将处理该事件,否则由路由器处理。
这是我当前的代码。
// router.js
define('router', [
'jquery'
, 'underscore'
, 'backbone'
, 'SomeView'
], function (
$, _, backbone, SomeView
) {
var router;
router = backbone.Router.extend({
routes: {
'some-view': someView
, 'some-view/:tab': someView
}
, initialize: function () {
}
, someView: function (tab) {
var view;
view = new SomeView(tab);
view.on('router:changeTab', function (tab) {
that.navigate('some-view/' + tab);
});
}
});
return router;
});
// someView.js
define('SomeView', [
'jquery'
, 'underscore'
, 'backbone'
], function (
$, _, backbone
) {
var SomeView;
SomeView = backbone.View.extend({
initialize: function (options) {
this.tab = options.tab;
}
, render: function (callback) {
// show the initial tab if given
if (this.tab) {
setTimeout(function () {
that.$el.find('[href="#' + that.tab + '-tab"]').click();
}, 0);
}
return this;
}
, events: {
, 'click .nav-tabs>li>a': 'showTab' // enable tabs
}
, showTab: function (e) {
var that, tab, tabs;
that = this;
e.preventDefault();
$(this).tab('show'); // I'm using bootstrap tab plugin
// update hash
tab = $(e.currentTarget).attr('href').split('-')[0].split('#')[1];
that.trigger('router:changeTab', tab);
// What I didn't know is how to prevent the handler from being
// invoked when the user press backward/forward button on the browser,
// and let this view handle it (show the corresponding tab).
}
return SomeView;
});