一个“;监听路由器”;(响应视图/模型中的路由器事件)

How does one "listen to the router" (respond to Router events in Views/Models) in Backbone.js?

本文关键字:路由器 模型 事件 响应 监听 一个 视图      更新时间:2023-09-26

在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);
    },
...