Reputation: 43
I'm new to Backbone and Laravel so this may be a simple question, but I need my Backbone router to match a URL on initial page load, e.g. localhost/search/query and I'd ideally like to do this without frag identifiers (or # hashtags or whatever). This is giving me two problems:
When I use Backbone.history.start({ pushState: true })
I get a 404 error from Laravel. Is there a way to define a default (index) route for all URLs in Laravel so I won't have to list every possible URL combination I may use?
When I don't use pushState: true
my Backbone router works fine but only if I don't navigate directly to the URL. For example, if I first go to localhost, then localhost/#search/example it works but if I go directly to localhost/#search/example the search route isn't triggered. I think this may be because I only start Backbone.history on document ready but I'm not sure how else to do this. Anyway, here's some code:
//app.js
window.App = {
Models: {},
Collections: {},
Views: {},
Router: {}
};
window.vent = _.extend({}, Backbone.Events);
// router.js
App.Router = Backbone.Router.extend({
routes: {
'': 'index',
'search/:query': 'search'
},
index: function() {
console.log('the index page');
},
search: function(query) {
console.log('the search page: ' + query);
vent.trigger('router:search', query);
}
});
// setup.js
(function() {
App.cats = new App.Cats();
App.appView = new App.AppView();
App.router = new App.Router;
Backbone.history.start({
pushState: true
});
})();
Thanks in advance for any advice!
Upvotes: 1
Views: 1374
Reputation: 38140
You can define a default route with "*actions":
http://backbonetutorials.com/what-is-a-router/
var AppRouter = Backbone.Router.extend({
routes: {
"*actions": "defaultRoute" // matches http://example.com/#anything-here
}
});
You could also define your starting root:
Backbone.history.start({pushState: true, root: "/public/search/"})
And you have to redirect your requests to your index.php
http://www.elcoderino.com/laravel-redirect-redirects-url-to-index-php/
Create .htaccess file in your public directory and add this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Upvotes: 1