简体   繁体   中英

How to get Backbone.js Router to trigger on default/index (no #tag hashtag) in CodeIgniter

I have a CodeIgniter app using .htaccess to remove index.php from the url so they look like this:

http://example.com/admin/
http://example.com/admin/users
http://example.com/admin/reports
http://example.com/admin/files

With http://example.com/admin/files being a single page backbone app, I need to show a list of files by default. Then http://example.com/admin/files#file/123 would edit a specific file.

Here is my Backbone Router:

App.Router = Backbone.Router.extend({
    routes: {
      ''         : 'files',
      'file/:id' : 'file'
    },

    files: function(){
      $(document.body).append("Files route has been called..");
    },

    file: function(id){
      $(document.body).append("File route called with id:" + id);
    }

});
new App.Router;
Backbone.history.start();

I can get the "file" route to trigger with:

http://example.com/admin/files#file/33

However, http://example.com/admin/files is completely ignored by the Backbone Router.

How can I get the default or index Backbone.js route to trigger when using CodeIgniters RewriteRule that eliminates the index.php file?

UPDATE: I'm very new at Backbone.js so still learning. I discovered if I change:

Backbone.history.start();

to:

Backbone.history.start({root: "/admin/files/" });

It works correctly. :)

The Backbone Router works with the browsers history api where it uses hash names (#something) to represent some state on the client. Initially, /admin/files is a route on the server and ignored on the client so you won't be able to use the Router for the files route. Since your page is rendered for the server route, I would just run whatever code you need to run on page load. I think that is what you want. If you need someway to get back to this initial "files" state, then you probably add an index route so that it would show up like /admin/files#index which would get you back to when the page first initially loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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