[英]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.