Routing Cakephp with BACKBONE JS - backbone.js

<script>
var HomeView = Backbone.View.extend({
template: '<h1>Home</h1>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var AboutView = Backbone.View.extend({
template: '<h1>About</h1>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var AppRouter = Backbone.Router.extend({
routes: {
'': 'homeRoute',
'home': 'homeRoute',
'about': 'aboutRoute',
},
homeRoute: function () {
var homeView = new HomeView();
$(".content").html(homeView.el);
},
aboutRoute: function () {
var aboutView = new AboutView();
$(".content").html(aboutView.el);
}
});
var appRouter = new AppRouter();
Backbone.history.start();
</script>
<ul>
<li><?php echo $this->Html->link('Home',array('controller' =>'pages','action' => 'home')); ?></li>
<li><?php echo $this->Html->link('About',array('controller' =>'pages','action' => 'about')); ?></li>
</ul>
How to convert the code above to make backbone.js like this in manual coding I seen in the NET.
<div id="navigation">
Home
About
</div>
<div class="content">
</div>
Im just new to this one guys please help me. Im reading Backbone js now, can anybody help me with this problem. If you have experience with cakephp backbone js.. I also wanted using it on CRUD cakephp.

Just a friendly reminder: CakePHP is a server-side library whose responsibility is to send HTML or some serialized data (JSON, XML, binary, etc.) to your browser.
backbone.js is a client-side library that provides building blocks for client-side content and event-handling. The only relationship between CakePHP and backbone.js is that CakePHP is perhaps responsible for delivering whatever scripts and assets your client needs. There is probably nothing that you can learn about backbone.js that is specific to CakePHP. So try to think in terms of "client" and "server" rather than backbone and Cake.
Now, almost every web site will have some links. When a user clicks a link the browser treats it as an event and responds accordingly.
JavaScript clients can extend the browser functionality by getting in between the browser and the event - that is, by telling the browser, "I will handle this event, not you."
In backbone.js, the Backbone.history.start method is what tells the browser to back off and let backbone take care of certain events:
window.onhashchange: This is supported by all browsers and is called whenever the "hash" part of the URL changes; for instance, if you click an anchor link Go somewhere the event will fire and the listener will be called. If the listener returns something other than true then the browser will not handle the event as usual, but otherwise, your browser URL will change to /path/to/page#somewhere
history.pushState and window.onpopstate: This is a new feature in HTML5 so it is not supported by older browsers, but at this point, it is fairly widely-adopted and available. Basically, this is a powerful API that gives client developers a way to manipulate and rewrite the history of a browser's navigation - not just the hash part of the URL, the whole thing - using syntax (see link) like history.pushState(undefined, undefined, 'not/a/real/path');. Correspondingly, there is an event handler window.onpopstate that will be called whenever the browser moves forward or backward in the history chain, but !NOT! when we call history.pushState or history.replaceState. This is a good behavior and by design.
You need to decide what you want to use - hash-style URLs and/or "real" URLs - and then configure Backbone.history.start arguments accordingly. You can use both but I don't recommend it.
Finally, please make sure **you are setting everything up in your JavaScript wrapped in a $(document).ready(function() { ... });. Right now you are not.

Related

Backbone.history is not updating in IE 9. Back button broken

In our app, we actually have two Backbone SPA applications. The first one is for login, registration and other features for unauthenticated users. The URL for this would be something like http://www.example.com/registration#signin. Once you login, you are redirected to our main Backbone app at http://www.example.com/ui#home.
In my main UI app, I am using Backbone.history without pushState. The App file looks something like:
define(function (require) {
var App = new Marionette.Application();
App.addInitializer(function (options) {
...
});
...
App.on('initialize:after', function () {
$(function(){
if (Backbone.history) {
Backbone.history.start({ root: '/ui' });
}
});
$.log("**WebApp**: Marionette app started.");
});
return App;
});
Of course, everything works flawlessly in any browser except IE 9 (and maybe 10, I need to check). In IE 9, all the routing works fine. Clicking links such as http://www.example.com/ui#anotherpage works. However, when the user clicks the Back button in their browser, they are not sent back to the last route fired. Instead, they are sent to http://www.example.com/registration#signin, which is the last page served by Node, our web server. As I click through links, I can see that history.length and Backbone.history.history.length are not updating.
All routes are fired from links/URL's. I'm not using router.navigate() within the code. Here are examples of our Router:
define(function (require) {
var Backbone = require('backbone'),
Marionette = require('marionette');
return Backbone.Marionette.AppRouter.extend({
appRoutes: {
"": "showHome",
"home": "showHome",
"foo": "showFoo"
}
});
});
And Controller:
define(function (require) {
var Backbone = require('backbone'),
Marionette = require('marionette');
return Backbone.Marionette.Controller.extend({
showHome: function () {
require(['webapp','modules/home'], function (WebApp) {
WebApp.module("Home").start();
WebApp.module("Home").controller.showModule();
});
},
showFoo: function () {
require(['webapp', 'modules/foo'], function (WebApp) {
WebApp.module("Foo").start();
WebApp.module("Foo").controller.showModule();
});
}
});
});
UPDATE:
On further research, it turns out the problem is that older versions of IE don't record hash changes in their history. See - Change location.hash and then press Back button - IE behaves differently from other browsers. But I'm still not sure what the workaround for this would be. I'm guessing it would somehow involve manually handling hash change events with a plugin such as jQuery Hashchange and doing... something? Manually setting IE's history? Or crafting a custom history object and using it when we detect a Back button in IE?
I was having the same problem in one of our apps for IE.
Starting backbone history like below works.
Backbone.history.start({
pushState: true,
hashChange: false
});
Update: As mentioned By T Nguyen,
When you set pushState to true, hash URL's no longer trigger routes. Unless you add server-side support for all your Backbone routes, you need to add an event handler on the client side which captures appropriate links and calls .navigate() on the route

Displaying backbone template in a new window

I need to open a backbone template in a new window. Is this possible? Currently I've got a template that is being displayed within a div but I need this content to display in a new window? I thought using a route might be the way to go but I'm not sure.
I'm a noob to backbone so there's probably a better way to do this.
In my view I've got:
events:
{
'click #active-bets' : 'loadActiveBetsPage',
}
loadActiveBetsPage: function(e)
{
var MyApp = new Backbone.Router();
MyApp.navigate('activebets', {trigger: true});
// , {trigger: true, target: "_blank"}
},
I thought I might get lucky and be able to pass a target: "_blank" parameter here.
in my routes sections:
var AppRouter = Backbone.Router.extend({
routes: {
":activebets" : "renderActiveBets",
"*actions" : "defaultRoute"
} });
app_router.on('route:renderActiveBets', function () {
$this.activeBetsView = new ActiveBetsView( { el: $this.elAccountInfo });
$this.activeBetsView.render();
/* thought something like this might help possibly
if ($(event.currentTarget).prop('target') === '_blank') {
return true;
}
*/
});`
Thank you in advance for any help on this one.
No, this is not possible and especially not with the Backbone Router directly.
The only ways to open new browser windows from a webpage are using the window.open javascript method. It will open a new browser window that directs to the URL specified. Note that the the page you have created and the page you started at are independent of each other and there is no way to communicate between them via javascript.
The other way is to have an anchor tag with the target -attribute, which results in clicking the link opening a new window/tab.
What you can do:
Use a dialog created with html to simulate a new window, e.g. jQuery UI Dialog
Create a separate webpage to display this information, open a new browser window and direct the new window to this webpage.
Update based on last comment:
"...there is no way to communicate between them via javascript."
Since HTML5, the solution for this is HTML5 Web Storage.
window.localStorage
is API that can communicate with all open tabs and windows in browser.

Backbonejs - should a change in the model cause the route to change, or should all changes be through the route first?

When a model is changed, I update the route (it has a url that contains the application's current state).
When a url is visited (or back is pressed) I update the model from the route.
This creates circular logic problems for me that I can't get my head around. Things are being changed twice for no reason.
Is it normal to base everything on the route, and use that to update the model?
Is it normal to have two models?
What is normal?
Any help or advice would be appreciated. Thanks
I wouldn't advise using Router the way you do. In general, the route action should not change model state. In general, HTTP GET operations should not have side-effects.
Routers should be used for navigation between different pages of a single-page application. Model changes should be triggered directly from the view code that handles user input. Let's say you have a model User, and view UserView, the view could work something like this:
var UserView = Backbone.View.extend({
events: {
"click #save", "save"
},
initialize: function(options) {
this.model = options.model;
},
render: function() {
//your render code here
},
save: function() {
var fields = {
name: this.$("#name").val();
email: this.$("#email").val();
};
this.model.save(fields , {
//after save go back to users page, or whatever
success: function() { window.location.hash = "/users"; },
error: this.displayError
});
}
});
Backbone isn't really an MVC framework, so the Router shouldn't be treated as a pure controller. And even if you did, changing state in a route action would be equivalent to changing state in a MVC controller GET endpoint - bad, bad idea.
If you want to adhere to a pure MVC pattern, you should implement your own controller layer, or look at another layer besides Backbone.

Backbone.js Pushstate: true not returning callback function

I am pretty new to backbone js and I am having some problem getting the pushstate functionality of my app to work. Here is an eg of my route:
var TodoRouter = new (Backbone.Router.extend({
routes: {
"": "index",
"item/add": "AddTodoItem",
"list/add": "AddTodoList"
},
AddTodoItem: function() {
//e.preventDefault();
alert("add new item");
},
AddTodoList: function(e) {
//e.preventDefault();
alert("add new list");
},
Start: function(){
//note: my directory structure is localhost/playground/todo/
Backbone.history.start({pushState: true, root: "/playground/todo/"});
},
initalize: function(){
},
index: function(){
var todoListView = new TodoListView({ collection: TodoItemCollection });
}
}));
Here is how I call my route:
$(function() {
TodoRouter.Start();
});
And lastly here is how I call a link:
New List
The problem that I am running into is that when I call the link, the page stays the same, no alert and the browser displays:
http://localhost/playground/todo/#list/add
Now here is the funny part, if I refresh the page, the url become:
http://localhost/playground/todo/list/add
and I get the alert. So I have a feeling I am missing a key point somewhere. Any help would be greatly appreciated!
You have pushState: true and that's why it preferred the slash / instead of hash #
Either change that or remove the hash
You're trying to use Backbone Routes and html5 pushState.
As the backbone documentation said:
"if you have a route of /documents/100, your web server must be able
to serve that page, if the browser visits that URL directly."
So if you want to trigger some functions through uri (localhost/webapp/#about) you just need to use Backbone Routes.
If you want to use Backbone Routes and pushState, you'll need a back-end to answer requests made to your readable url (localhost/webapp/about) and need to use backbone.navigate method to avoid the browser understand <a href="#someRoute"> as a html anchor.
here you can see a complete example
You can't trigger your route, because when pushState:true the href="#route" has the same behavior as a html anchor.

Backbone > Multiple Routers and History.start

I'd like to have multiple routers living on a single page for modularity. I initialize the routers on $(document).ready() in different js files. When I had just one router that worked fine because I could call History.start() right after initializing the router, but now that I have multiple routers that could be initialized from different files, I'm not sure when to call History.start().
For example:
<script src="router1.js" type="text/javascript"></script>
<script src="router2.js" type="text/javascript"></script>
In router1.js:
$(document).ready(function(){
new Core.Routers.Router1()
});
and likewise for router2.
Is the best solution just to add a new $(document).ready() that calls History.start() at the end of the page? I don't think the doc ready calls are blocking, so doesn't that introduce a race condition where all the Routers may not have been initialized by the time History.start() has been called.
You only need to call Backbone.history.start() once in your app and the only criteria for when you call it is that at least one router has to be instantiated already.
So, you could easily do this:
$(function(){
new MyRouter();
Backbone.history.start();
});
$(function(){
new AnotherRouter();
});
$(function(){
new AndMoreRouters();
});
I do a similar thing with routers on a regular basis, and I often start up new routers long after the page has been loaded and the user is interacting with the page.
FWIW though, you might be interested in the idea of initializers that I have in my Backbone.Marionette plugin and documented as part of this blog post: http://lostechies.com/derickbailey/2011/12/16/composite-javascript-applications-with-backbone-and-backbone-marionette/
You also may be able to check Backbone.History.started...
var Router = Backbone.Router.extend({
routes: {
'': 'load'
},
initialize: function () {
},
load: function () {
}
});
$(function () {
new Router();
if (!Backbone.History.started) {
Backbone.history.start();
}
});
It was added recently in a pull request.
Be sure and check out Derick's Marionette plugin as well, it's pretty awesome.

Resources