I'm going through examples with routing from David Sulc's book Backbone.Marionette.js: A Gentle Introduction

https://leanpub.com/marionette-gentle-introduction

ContactManager.navigate = function (route, options) {
    options || (options = {});
    Backbone.history.navigate(route, options);

};


ContactManager.getCurrentRoute = function () {
    return Backbone.history.fragment;
};


ContactManager.on("initialize:after", function () {

    if (Backbone.history) {
        Backbone.history.start();

        if (this.getCurrentRoute() === "") {
            ContactManager.trigger("contacts:list");

        }

    }

As you can see if the history fragment is empty, it will trigger the contacts:list event which will render the list of contacts. However, it doesn't redirect at all, and I've found out that fragment is preset to "contacts" somehow, so the event doesn't get fired at all. It also happened to me once that initially the fragment was empty and got everything rendered, and url changed properly, but upon refresh fragment was still "contacts" and again nothing was rendered.

 ContactsApp.Router = Marionette.AppRouter.extend({
        AppRoutes: {
            "contacts": "listContacts"

        }
    });

ContactManager.on("contacts:list", function () {
        ContactManager.navigate("contacts");
        API.listContacts();

    });

This is the code that handles the event. What seems to be the problem? Thanks.

有帮助吗?

解决方案

I think there is some missing code. I would expect to find something like this in the router:

var myController = {
    listContacts: function () {
        ContactManager.trigger("contacts:list");
    }
};

ContactsApp.Router = Marionette.AppRouter.extend({
    controller: myController,
    appRoutes: {
        "contacts": "listContacts"
    }
});

Note that appRoutes starts with a lowercase a.

Now the route contacts will call the controller's listContacts method and trigger the ContactManager.on("contacts:list"... callback, running the appropriate API method.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top