Backbone - Update URL from view function - backbone.js

I'm stumbling through my first backbone project, and am trying to update the URL after a button element is clicked.
I can manually set the URL via window.location.hash, but I assume this is not the correct way. Can anyone tell me what is the preferred way to update the URL?
var AppView = Backbone.View.extend({
events: {
"click #loadProject": "filterProject",
},
filterProject: function(){
var projectID = $('#selectProject option:selected').val();
var orgID = 'test';
// Is there a better way to do this?
window.location.hash = '/'+orgID+'/'+projectID;
this.renderProject(orgID,projectID);
},
renderProject:function(orgID,projectID){
//Some code
},
});
//Routing
var PropertiesRouter = Backbone.Router.extend({
routes: {
"/:who/:project":"getProjects", //#/org/1
"/:who":"getOrganisation", //#/org
"*actions": "defaultRoute"
},
getProjects:function(who,project){
app.renderProject(who,project);
},
getOrganisation:function(who){
app.renderOrganisation(who);
},
defaultRoute: function(actions){
app.renderHomePage();
},
});
var app = new AppView();
//create router instance
var propertiesRouter = new PropertiesRouter();
//start history service
Backbone.history.start();
Thanks!

You definitely can call window.location.hash, but this does break some of the separation backbone is trying to create for you. A better choice is to call router.navigate(..). See http://backbonejs.org/#Router-navigate

Related

Backbone Router -- load data

EDIT: Got it working, but it seems wrong.
I ending up adding a listener to the sync event on the main app view, then render a player. I also added a global variable PgaPlayersApp.CurrentPlayer.
Am I going about this the wrong way? What is the correct way to do this? Is there a reason I can't use reset: true and then listen for the reset event? (It doesn't work)
ROUTER:
// js/router.js
var PgaPlayersApp = PgaPlayersApp || {};
var Router = Backbone.Router.extend({
routes:{
'player/:id': 'loadPlayer'
},
loadPlayer: function(id)
{
PgaPlayersApp.CurrentPlayer.set('id', id);
PgaPlayersApp.CurrentPlayer.fetch();
}
});
PgaPlayersApp.Router = new Router();
Backbone.history.start();
VIEW:
//js/views/app.js
var PgaPlayersApp = PgaPlayersApp || {};
PgaPlayersApp.AppView = Backbone.View.extend({
el: '#pga_players_profile_app',
initialize: function()
{
this.listenTo(PgaPlayersApp.Players, 'reset', this.addAll);
this.listenTo(PgaPlayersApp.CurrentPlayer, 'sync', this.loadPlayer);
PgaPlayersApp.Players.fetch({reset: true});
},
...
loadPlayer: function()
{
new PgaPlayersApp.PlayerCardView({ model: PgaPlayersApp.CurrentPlayer }).render();
}
});
Backbone.js is a library that doesn't really enforce how you'd like to structure your App (Or the relationship between your Controller, Model, Router, etc.)
Below is one of the many ways to do it.
Couple highlights:
Router kicks off the fetch process.
When model has been fetched, Router then asks the View to render data (Instead of having the View listening to change events from the Model.)
This assumes that PlayerCardView is a "read only" view, as the View doesn't listen to change events from the Model. Depending on your use case, this might not be desirable, so it ultimately depends on how you'd like to handle it.
Here are some sample code:
(function (export) {
var App = export.App = {};
// Stores state/current views of the App
App.state = {};
App.state.currentPlayer = null;
// Model containing the player
App.PlayerModel = Backbone.Model.extend({});
// Single Player View (Assuming you have a collection view for list of players)
App.PlayerCardView = Backbone.View.extend({
model: App.PlayerModel,
template: _.template('<%= id %>'),
render: function(parentEl) {
// Render player
this.$el.html(this.template(this.model.toJSON()));
// Append player view to parent container
if (parentEl) {
parentEl.append(this.$el);
}
return this;
}
// Don't forget to clean up as well!
});
// Router
App.Router = Backbone.Router.extend({
routes: {
'player/:id': 'showPlayer'
},
showPlayer: function(id) {
// Unload current player view, if necessary
// Construct model
var player = App.state.currentPlayer = new App.Player({
id: id
});
// Pass model to the new player view
var view = App.state.currentPlayerView = new App.PlayerCardView({
model: App.state.currentPlayer
});
// At this time, you should probably show some loading indicator as you're fetching data from the server
// Fetch data
player.fetch({
success: function() {
// This would be called when data has been fetched from the server.
// Render player on screen
view.render($('#parentContainerId'));
}
});
}
});
// Initializes the App
App.init = function() {
// Kick off router
App.state.router = new App.Router();
export.Backbone.history.start();
};
})(window);
// Start the app!
window.App.init();
Gist: https://gist.github.com/dashk/5770073

Getting actions to fire with backbone

Iv'e set up my first little backbone app with a router to see if i can get some actions firing. I can't. I don't get an error message, but the console.log messages aren't displaying. Is there something more I have to set up to get the app started?
window.BreakfastApp = new (Backbone.Router.extend({
routes: { "": "interest", "products/:type": "products"},
initialize: function(){
console.log("hello world");
},
start: function(){
Backbone.history.start({pushState: true});
},
interest: function(){
console.log('interest')
},
products: function(type){
console.log('product' + type )
},
toppings: function(){
console.log('toppings')
},
results: function(){
console.log('results')
}
}));
$(function(){
BreakfastApp.start();
});
The documentation says:
During page load, after your application has finished creating all of
its routers, be sure to call Backbone.history.start(), or
Backbone.history.start({pushState: true}) to route the initial URL.
In your case something like:
var BreakfastAppRouter = Backbone.Router.extend({
...
});
var router = new BreakfastAppRouter();
Backbone.history.start();
should do the job.

Strange behaviour of this in backbone.js Controller

Yes I am new to JS and also in backbonejs.
Lets dig into the problem now.
I am having a very strange behaviour of this in backbonejs Controller.
Here is the code of my controller
var controller = Backbone.Controller.extend( {
_index: null,
routes: {
"": "index"
},
initialize: function(options){
var self = this;
if (this._index === null){
$.getJSON('data/album1.json',function(data) {
//this line is working self._index is being set
self._index = new sphinx.views.IndexView({model: self._photos});
});
Backbone.history.loadUrl();
}
},
index: function() {
//this line is not working
//here THIS is pointing to a different object
//rather than it was available through THIS in initialize method
this._index.render();
}
});
Here is the lines at the end of the file to initiate controller.
removeFallbacks();
gallery = new controller;
Backbone.history.start();
Now , i am missing something. But what ???
If this is the wrong way what is the right way??
I need to access the properties i set from the initialize method from index method.
It looks like the caller function of index method is changing it's scope.
I need to preserve the scope of that.
You have to specify the route action into a Backbone Route not into a Controller. Inside the router is where you are going to initialize your controller and views.
Also, there is no method Backbone.history.loadURL(). I think you should use instead Backbone.history.start() and then call the navigate in the router instance e.g. router.navigate('state or URL');
var myApp = Backbone.Router.extend( {
_index: null,
routes: {
"": "index"
},
initialize: function(options){
//Initialize your app here
this.myApp = new myApp();
//Initialize your views here
this.myAppViews = new myAppView(/* args */);
var self = this;
if (this._index === null){
$.getJSON('data/album1.json',function(data) {
//this line is working self._index is being set
self._index = new sphinx.views.IndexView({model: self._photos});
});
Backbone.history.loadUrl(); //Change this to Backbone.history.start();
}
},
// Route actions
index: function() {
this._index.render();
}
});

Roles of backbone views, model, and router

I am developing a backbone application which is using require.js.
I want a user to enter in the 'id' for a model and then either be redirected to a view for that model if it exists, or display an error message if it does not. This sounds extremely simple, but I am having trouble figuring out the roles of each component.
In the application below, the user will come to an index page with an input (with id 'modelId') and a button (with class attribute 'lookup').
The following piece of code is the router.
define(['views/index', 'views/myModelView', 'models/myModel'],
function(IndexView, MyModelView, myModel) {
var MyRouter = Backbone.Router.extend({
currentView: null,
routes: {
"index": "index",
"view/:id": "view"
},
changeView: function(view) {
if(null != this.currentView) {
this.currentView.undelegateEvents();
}
this.currentView = view;
this.currentView.render();
},
index: function() {
this.changeView(new IndexView());
},
view: function(id) {
//OBTAIN MODEL HERE?
//var model
roter.changeView(new MyModelView(model))
}
});
return new MyRouter();
});
The following piece of code is the index view
define(['text!templates/index.html', 'models/myModel'],
function( indexTemplate, MyModel) {
var indexView = Backbone.View.extend({
el: $('#content'),
events: {
"click .lookup": "lookup"
},
render: function() {
this.$el.html(indexTemplate);
$("#error").hide();
},
lookup: function(){
var modelId = $("#modelId").val()
var model = new MyModel({id:modelId});
model.fetch({
success: function(){
window.location.hash = 'view/'+model.id;
},
error: function(){
$("#error").text('Cannot view model');
$("#error").slideDown();
}
});
},
});
return indexView
});
What I can't figure out is that it seems like the better option is for the index view to look up the model (so it can display an error message if the user asks for a model that doesn't exist, and also to keep the router cleaner). But the problem is that the router now has no reference to the model when the view/:id router is triggered. How is it supposed to get a hold of the model in the view() function?
I guess it could do another fetch, but that seems redundant and wrong. Or maybe there is supposed to be some global object that both the router and the view share (that the index view could put the model in), but that seems like tight coupling.
You can do something like this. You could do something similar with a collection instead of a model, but it seems like you don't want to fetch/show the whole collection?
With this type of solution (I think similar to what #mpm was suggesting), your app will handle browser refreshes, back/forward navigation properly. You basically have a MainView, which really acts more like a app controller. It handles events triggered either by the router, or by user interaction (clicking lookup or a back-to-index button on the item view).
Credit to Derick Bailey for a lot of these ideas.
In the Router. These are now only triggered if the user navigates by changing a URL or back/forward.
index: function() {
Backbone.trigger('show-lookup-view');
},
view: function(id) {
var model = new MyModel({id: id});
model.fetch({
success: function(){
Backbone.trigger('show-item-view', model);
},
error: function(){
// user could have typed in an invalid URL, do something here,
// or just make the ItemView handle an invalid model and show that view...
}
});
}
In new MainView, which you would create on app startup, not in router:
el: 'body',
initialize: function (options) {
this.router = options.router;
// listen for events, either from the router or some view.
this.listenTo(Backbone, 'show-lookup-view', this.showLookup);
this.listenTo(Backbone, 'show-item-view', this.showItem);
},
changeView: function(view) {
if(null != this.currentView) {
// remove() instead of undelegateEvents() here
this.currentView.remove();
}
this.currentView = view;
this.$el.html(view.render().el);
},
showLookup: function(){
var view = new IndexView();
this.changeView(view);
// note this does not trigger the route, only changes hash.
// this ensures your URL is right, and if it was already #index because
// this was triggered by the router, it has no effect.
this.router.navigate('index');
},
showItem: function(model){
var view = new ItemView({model: model});
this.changeView(view);
this.router.navigate('items/' + model.id);
}
Then in IndexView, you trigger the 'show-item-view' event with the already fetched model.
lookup: function(){
var modelId = $("#modelId").val()
var model = new MyModel({id:modelId});
model.fetch({
success: function(){
Backbone.trigger('show-item-view', model);
},
error: function(){
$("#error").text('Cannot view model');
$("#error").slideDown();
}
});
},
I don't think this is exactly perfect, but I hope it could point you in a good direction.

Fetch backbone collection fail from django-tastypie

I'm using backbone-tastypie from https://github.com/PaulUithol/backbone-tastypie, and I can't fetch a collection data.
Thats my code:
var User = Backbone.Model.extend({
url: '/api/v1/user'
});
var HoraExtra = Backbone.Model.extend({
url: '/api/v1/horasextra/'
});
var HorasExtra = Backbone.Collection.extend({
url: '/api/v1/horasextra/',
model: HoraExtra
});
var Horas = new HorasExtra();
var activeUser = new User();
var HorasExtraView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, "render");
},
render: function() {
var plantilla = Handlebars.compile($("#horas_extra_template").html());
var html = plantilla(Horas);
this.$el.html(html);
console.log(JSON.stringify(Horas));
}
});
var HorasExtraWidget = new HorasExtraView({el: $('#base')});
Horas.fetch({
data: {
"usuario__id": 2,
"hor_com__month": 11
}
});
HorasExtraWidget.render();
And that's the result of console.log(JSON.stringify(Horas):
[]
Many thanks
I would suggest to you that you take tastypie, backbone and build your own simple project in 1-2 days.
Then you will get to know basic issues of coupling those 2 frameworks.
Without that knowledge it is pointless you try out other people's projects and then wonder "what isn't working".
And from my personal experience, both tastypie and javascript are pretty straightforward and are easy to couple.
And I am NOT an expert.
couple of points: try explicitly fetching models with fetch, manipulate fetched model from success callback, and watch your model url's, forward slashes in them etc.
Seems your collection is empty.
See in console if there is a GET call to server.
If not, you're not actually fetching anything from the server.
I used https://github.com/amccloud/backbone-tastypie and then your code should look like this, I guess. Not tested.
var HorasCollection = Backbone.Tastypie.Collection.extend({
url: '/api/v1/horasextra/'
});
var HorasExtraView = Backbone.View.extend({
el: $('#base'),
entries: new HorasCollection(),
render: function() {
var that = this;
this.entries.fetch({
success: function(entries){
console.log("Entries", entries.models);
// var t = _.template(template, {hello: 'world'});
// that.$el.html(t);
},
error: function(model, response){
console.log("Error", response);
}
});
}
});
If you're trying to create a table for your data, try my jquery plugin :)
https://github.com/sspross/tastybackbonepie

Resources