m_v*_*eek 4 routes backbone.js marionette
我在Backbone.js/Marionette.js中有三个关于路由的问题:
例如,对于Express.js(在Node.js中),它将是app.routes.
我正在尝试使用Backbone.js/Marionette.js做同样的事情,但找不到任何执行此操作的属性或方法.
我发现以下脚本是Backbone路由器的原型,但它更像是一个黑客而不是一个稳定的解决方案:没有哈希URL的简单骨干路由
我所说的子路由器是一个只处理网址的一部分的路由器,例如:
var AppRouter = Backbone.Router.extend({
routes: {
'articles' : 'MyArticleRouter'
}
});
var MyArticleRouter = Backbone.Router.extend({
routes: {
'science' : 'someMethod',
'literrature' : 'someOtherMethod'
}
});
Run Code Online (Sandbox Code Playgroud)
这将通过让我在类别特定的子路由器中定义AppRouter中的主要路由和所有子路由(在第二个斜杠"/"之后的部分)来对我的URL进行更多分类.
因此对于以下URL:"hostname/articles/science",路由过程看起来像这样:
先感谢您 !
回答#1:
所有路线都已注册Backbone.history.handlers.
回答#2:
您可以为站点中的每个链接添加处理程序:
var application = new Backbone.Marionette.Application();
application.addInitializer(function(options) {
// Add class to target a browser, not as standalone app.
if(window.navigator.standalone != true) {
$('body').addClass('no-standalone');
}
// Prevent internal links from causing a page refresh.
$(document).on('click', 'a', function(event) {
var fragment = Backbone.history.getFragment($(this).attr('href'));
var matched = _.any(Backbone.history.handlers, function(handler) {
return handler.route.test(fragment);
});
if (matched) {
event.preventDefault();
Backbone.history.navigate(fragment, { trigger: true });
}
});
});
Run Code Online (Sandbox Code Playgroud)
当然请确保使用pushState:
if (!Backbone.history.started) {
Backbone.history.start({ pushState: true });
}
Run Code Online (Sandbox Code Playgroud)
在初始化所有路由器之后必须运行最后一个片段.
回答#3:
这可能有点分裂您的路线:
define([
'backbone',
'underscore',
'routers/dashboard',
'routers/anotherroute1',
'routers/anotherroute2'
],
function(Backbone, _, DashboardRouter, AnotherRoute1, AnotherRoute2) {
'use strict';
var application = new Backbone.Marionette.Application();
application.addInitializer(function () {
_.each([DashboardRouter, AnotherRoute1, AnotherRoute2], function(router) {
new router();
});
if (!Backbone.history.started) {
Backbone.history.start({ pushState: true });
}
});
return application;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4904 次 |
| 最近记录: |