我已经开始熟悉backbone.js,需要一点时间来绕过路由器,模型和视图。
通过路由器处理路由并定义它们是小菜一碟,直到特定路由定义为<a href="#some-url">
(我不确定100%,但我认为骨干网覆盖了默认链接行为,而是重定向它动态加载模板停留在当前页面上。)
我需要的是在用户点击div元素时执行的acton。在视图下添加事件很容易,并且单击正确调用该函数的div。
但从那时起我不知道该怎么做。我可以轻松地添加:window.location.href = "#some-url"
,浏览器会将页面重定向到要求的href,但这似乎打破了单页面规则主干试图创建。
是否有更合适的方法来处理视图更改,而不是强制浏览器通过window.location更改href?
编辑:添加了代码。
app.js
require(['jquery', 'backbone', 'app/router'], function ($, Backbone, Router) {
window.router = new Router();
Backbone.history.start();
});
应用程序/ router.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();
});
},
...
应用程序/路由器/视图/ home.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 } )
}
});
答案 0 :(得分:2)
让我们说你已经像这样定义了你的路由器
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
});
结帐主干docs了解更多信息。
修改
...
//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
}