我已经开始熟悉骨干网.js需要一点时间来了解路由器、型号和视图。
通过路由器处理路由并定义它们是小菜一碟,直到该特定路由被定义为<a href="#some-url">
(我不确定 100%,但我认为主干网正在覆盖默认链接行为,而是重定向它动态加载模板留在当前页面上)。
我需要的是在用户单击div 元素时执行的操作。很容易在视图下添加事件,并正确单击div 调用该函数。
但从那时起,我就不知道该怎么办。我可以很容易地添加:window.location.href = "#some-url"
,浏览器会将页面重定向到询问的href,但这似乎是打破单页规则骨干试图创建的。
有没有比强制浏览器通过 window.location 更改 href 更合适的方法来处理视图更改?
编辑:添加了代码。
应用.js
require(['jquery', 'backbone', 'app/router'], function ($, Backbone, Router) {
window.router = new Router();
Backbone.history.start();
});
应用/路由器.js
var $ = require('jquery'),
Backbone = require('backbone'),
HomeView = require('app/views/Home'),
$body = $('body'),
homeView = new HomeView({el: $body});
...
return Backbone.Router.extend({
routes: {
"": "home",
"about": "about"
},
home: function () {
homeView.delegateEvents();
homeView.render();
},
about: function () {
require(["app/views/About"], function (AboutView) {
var view = new AboutView({el: $body});
view.render();
});
},
...
应用程序/路由器/视图/主页.js
return Backbone.View.extend({
events: {
"click #about": "followAbout"
},
render: function () {
this.$el.html(template());
return this;
},
followAbout: function () {
console.log('about');
window.router.navigate( "about", { trigger: true } )
}
});
假设您已经像这样定义路由器
var Workspace = Backbone.Router.extend({
routes: {
"help": "help", // #help
"search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
},
help: function() {
...
},
search: function(query, page) {
...
}
});
然后创建了路由器的新实例
router = new Workspace();
Backbone.history.start();
在您的div 中,您可以选择在数据属性中定义您的路线,这对您来说很方便,这样会很方便
<div id="my_div" data-path="some-url">
...
</div>
当用户单击div 时,您可以从其数据中获取路由navigate
并使用函数像这样转到该路由。
$("#my_div").on('click', function(e){
var path = $(this).attr("data-path");
router.navigate(path, { trigger: true});
//this will navigate to the path like a single page app without reloading the page
});
查看主干文档了解更多信息。
编辑
...
//events inside first view
'click #div-1': 'myFunction'
//myfunction code
myFunction: function(e){
clicked_div = e.currentTarget;
path = $(clicked_div).attr('data-path'); //I'm assuming you've stroed the path in your div, or you can get it how ever you like
window.router.navigate(path, {trigger: true});
//Also I am assuming you've defined your router under the window object directly, so it can be accessed directly. Or you can always namespace it in an object
//, to avoid collision
}