[英]How does one “listen to the router” (respond to Router events in Views/Models) in Backbone.js?
在Backbone.js文档中,在Router.routes方法的条目中说明了这一点
当访问者按下后退按钮或输入URL,并且匹配特定路由时,操作的名称将作为事件触发,以便其他对象可以侦听路由器并得到通知。
我试图在这个相对简单的例子中实现它:
相关的JS:
$(document).ready(function(){
// Thing model
window.Thing = Backbone.Model.extend({
defaults: {
text: 'THIS IS A THING'
}
});
// An individual Thing's View
window.ThingView = Backbone.View.extend({
el: '#thing',
initialize: function() {
this.on('route:showThing', this.anything);
},
anything: function() {
console.log("THIS DOESN'T WORK! WHY?");
},
render: function() {
$(this.el).html(_.template($('#thing-template').html(), {
text: this.model.get('text')
}));
return this;
}
});
// The Router for our App
window.ThingRouter = Backbone.Router.extend({
routes: {
"thing": "showThing"
},
showThing: function() {
console.log('THIS WORKS!');
}
});
// Modified from the code here (from Tim Branyen's boilerplate)
// http://stackoverflow.com/questions/9328513/backbone-js-and-pushstate
window.initializeRouter = function (router, root) {
Backbone.history.start({ pushState: true, root: root });
$(document).on('click', 'a:not([data-bypass])', function (evt) {
var href = $(this).attr('href');
var protocol = this.protocol + '//';
if (href.slice(protocol.length) !== protocol) {
evt.preventDefault();
router.navigate(href, true);
}
});
return router;
}
var myThingView = new ThingView({ model: new Thing() });
myThingView.render();
var myRouter = window.initializeRouter(new ThingRouter(), '/my/path/');
});
相关的HTML:
<div id="thing"></div>
<!-- Thing Template -->
<script type="text/template" id="thing-template">
<a class='task' href="thing"><%= text %></a>
</script>
但是,View的初始化函数中引用的路由器事件似乎没有被提取(其他一切正常 - 我成功调用了路由器中定义的“showThing”方法)。
我相信我必须对本声明所描述的文件有一些误解。 因此,我在回复中寻找的是:我希望有人修改我的代码,以便通过View拾取的路由器事件工作,或者清楚地解释我上面列出的路由器文档是什么意思我们要做的,理想情况下使用替代代码样本(或使用我的,修改过的)。
非常感谢您提供的任何帮助!
这是因为您将侦听器绑定到错误的对象。 在您的视图中尝试此操作:
window.ThingView = Backbone.View.extend({
initialize: function() {
myRouter.on('route:showThing', this.anything);
},
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.