一个“;监听路由器”;(响应视图/模型中的路由器事件)
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的initialize函数中引用的router事件似乎没有被接收到(其他一切都正常——我成功地调用了router中定义的"showThing"方法)。
我相信我一定对这份声明的文件意图有一些误解。因此,我想要的回应是:我希望有人修改我的代码,使其通过视图接收的路由器事件工作,或者,清楚地解释我上面列出的路由器文档打算我们做什么,最好是使用替代代码示例(或使用我的,修改)。
非常感谢您能提供的任何帮助!
这是因为您将侦听器绑定到了错误的对象。在你的视图中试试这个:
window.ThingView = Backbone.View.extend({
initialize: function() {
myRouter.on('route:showThing', this.anything);
},
...
相关文章:
- 有没有任何方法可以将控制器从文件加载到ui路由器$stateProvider中
- 在VanillaJS中模拟模型双向数据绑定
- AngularJS UI路由器不能像ng路由器那样工作
- 为集合分配大量的模型弹药
- 如何使用backbone.js从集合中获取模型名称
- 反应路由器弄乱了请求网址
- 如何使用带有Preact的React路由器
- 骨干模型默认值-todos.js示例中不必要的代码
- EmberJS中支持单字母单词模型
- 2个backbone.js集合,具有相同的模型,但排序顺序不同
- 将不在模型中的数据返回到mvc控制器
- 如何在视图模型contet更新更新上调用Jquery函数
- 通过当前路由器's模型转换为Ember.js中创建的对象
- 如何将值与$scope绑定,以从定义状态ui路由器的控制器中使用ng模型进行查看
- 正在加载ui路由器状态下的共享模型
- 一个“;监听路由器”;(响应视图/模型中的路由器事件)
- Ember 2.0路由器不加载模型数据
- 在ui路由器中的状态之间共享ng模型数据
- 将数据推送到以路由器为骨干的模型
- 主干:如何通过路由器在视图中只获取和显示一个模型数据