简体   繁体   English

如何在Backbone.js中“监听路由器”(响应视图/模型中的路由器事件)?

[英]How does one “listen to the router” (respond to Router events in Views/Models) in Backbone.js?

In the Backbone.js documentation, in the entry for the Router.routes method , it is stated 在Backbone.js文档中,在Router.routes方法的条目中说明了这一点

When the visitor presses the back button, or enters a URL, and a particular route is matched, the name of the action will be fired as an event, so that other objects can listen to the router, and be notified. 当访问者按下后退按钮或输入URL,并且匹配特定路由时,操作的名称将作为事件触发,以便其他对象可以侦听路由器并得到通知。

I have attempted to implement this in this relatively simple example: 我试图在这个相对简单的例子中实现它:

The relevant JS: 相关的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/');
});

The relevant HTML: 相关的HTML:

  <div id="thing"></div>

  <!-- Thing Template -->
  <script type="text/template" id="thing-template">
    <a class='task' href="thing"><%= text %></a>
  </script>

However, the router event referenced in the View's initialize function does not seem to get picked up (everything else works--I'm successfully calling the "showThing" method defined in the Router). 但是,View的初始化函数中引用的路由器事件似乎没有被提取(其他一切正常 - 我成功调用了路由器中定义的“showThing”方法)。

I believe I must have some misconception about what the documentation intended by this statement. 我相信我必须对本声明所描述的文件有一些误解。 Therefore, what I'm looking for in a response is: I'd love to have someone revise my code so that it works via a Router event getting picked up by the View , or, clearly explain what the Router documentation I listed above intends us to do, ideally with an alternative code sample (or using mine, modified). 因此,我在回复中寻找的是:我希望有人修改我的代码,以便通过View拾取路由器事件工作,或者清楚地解释我上面列出的路由器文档是什么意思我们要做的,理想情况下使用替代代码样本(或使用我的,修改过的)。

Many thanks in advance for any assistance you can provide! 非常感谢您提供的任何帮助!

This is beacuse you are binding a listener to the wrong object. 这是因为您将侦听器绑定到错误的对象。 Try this in your View : 在您的视图中尝试此操作:

window.ThingView = Backbone.View.extend({

    initialize: function() {
            myRouter.on('route:showThing', this.anything);
    },

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM