Sorting a Collection in Backbone - javascript

Ok so I have an API that returns a JSON feed of podcasts.
These podcasts show up on the frontend, but the order is in the exact opposite order that I need. I'm even more confused because the JSON feed it's calling is in the correct order I want but I can't get it to work like that on the frontend. Please take a look at the code I'm working with:
http://pastebin.com/bSamtFUw
var cache = new CacheProvider;
var Photo = Backbone.Model.extend({
subalbum: function() { return 'c' + gallery._currentsub; }
});
var PhotoCollection = Backbone.Collection.extend({
model: Photo,
comparator: function(item) {
return item.get('pid');
}
});
function removeFallbacks(){
var query = $('.jstest,.gallery');
if(query.length){
query.remove();
}
}
var IndexView = Backbone.View.extend({
el: $('#main'),
indexTemplate: $("#indexTmpl").template(),
render: function() {
removeFallbacks();
var sg = this;
this.el.fadeOut('fast', function() {
sg.el.empty();
$.tmpl(sg.indexTemplate, sg.model.toArray()).appendTo(sg.el);
sg.el.fadeIn('fast');
});
return this;
}
});
var SubalbumView = Backbone.View.extend({
el: $('#main'),
indexTemplate: $("#subindexTmpl").template(),
initialize: function(options){
},
render: function() {
var sg = this;
removeFallbacks();
this.el.fadeOut('fast', function() {
sg.el.empty();
$.tmpl(sg.indexTemplate, sg.model.toArray()).appendTo(sg.el);
sg.el.fadeIn('fast');
});
return this;
}
});
var PhotoView = Backbone.View.extend({
el: $('#main'),
itemTemplate: $("#itemTmpl").template(),
initialize: function(options) {
this.album = options.album;
},
render: function() {
var sg = this;
removeFallbacks();
this.el.fadeOut('fast', function() {
sg.el.empty();
$.tmpl(sg.itemTemplate, sg.model).appendTo(sg.el);
sg.el.fadeIn('fast');
});
return this;
}
});
var Gallery = Backbone.Controller.extend({
_index: null,
_photos: null,
_album :null,
_subalbums:null,
_subphotos:null,
_data:null,
_photosview:null,
_currentsub:null,
routes: {
"": "index",
"subalbum/:id": "hashsub",
"subalbum/:id/" : "directphoto",
"subalbum/:id/:num" : "hashphoto"
},
initialize: function(options) {
var ws = this;
if (this._index === null){
$.ajax({
url: 'http://mikegradio.com/api/v1/podcasts/export/?tags__title=sports&sort_by=-rank&limit=50',
dataType: 'json',
data: {},
success: function(data) {
ws._data = data;
ws._photos = new PhotoCollection(data);
ws._index = new IndexView({model: ws._photos});
Backbone.history.loadUrl();
}
});
return this;
}
return this;
},
index: function() {
this._index.render();
},
hashsub:function(id){
var properindex = id.replace('c','');
this._currentsub = properindex;
this._subphotos = cache.get('pc' + properindex) || cache.set('pc' + properindex, new PhotoCollection(this._data[properindex].subalbum));
this._subalbums = cache.get('sv' + properindex) || cache.set('sv' + properindex, new SubalbumView({model: this._subphotos}));
this._subalbums.render();
},
directphoto: function(id){
},
hashphoto: function(num, id){
this._currentsub = num;
num = num.replace('c','');
if(this._subphotos == undefined){
this._subphotos = cache.get('pc' + num) || cache.set('pc' + num, new PhotoCollection(this._data[num].subalbum));
}
this._subphotos.at(id)._view = new PhotoView({model: this._subphotos.at(id)});
this._subphotos.at(id)._view.render();
}
});
gallery = new Gallery();
Backbone.history.start();
http://pastebin.com/VZ6aTj9T#
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="gallery.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="shadows.css" type="text/css" media="screen" charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="buttons.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="ipad.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="desktop.css" type="text/css" media="screen" charset="utf-8" />
<script id="indexTmpl" type="text/x-jquery-tmpl">
<div class="item drop-shadow round">
<div class="item-image">
<a href="#subalbum/${cid}"><img src="${attributes.image}" alt="${attributes.title}" />
</a>
</div>
</div>
</script>
<script id="subindexTmpl" type="text/x-jquery-tmpl">
<div class="track drop-shadow round">
<div class="item-image subalbum">
<div class="item-artist">${attributes.title}</div>
<audio controls preload="none" id="audioControl" id="audio-player" src="${attributes.media}" type="audio/mp3" controls="controls"></audio>
<div class="item-price">${attributes.duration}</div>
Shop
</div>
</div>
</script>
<script id="itemTmpl" type="text/x-jquery-tmpl">
<div class="item-detail">
<div class="item-image drop-shadow round"><img src="${attributes.large_image}" alt="${attributes.title}" /></div>
<div class="item-info">
<div class="item-artist">${attributes.artist}</div>
<div class="item-title">${attributes.title}</div>
<div class="item-price">$${attributes.price}</div>
<br />
<div class="item-link">Buy this item</div>
<div class="back-link">« Back to Albums</div>
</div>
</div>
</script>
</head>
<body>
<div id="container">
<div id="main">
</div>
</div>
<script src="LAB.min.js" type="text/javascript"></script>
<script type="text/javascript">
$LAB
.script("jquery-1.4.4.min.js").wait()
.script("jquery.tmpl.min.js")
.script("underscore-min.js")
.script("backbone-min.js")
.script("cacheprovider.js").wait()
.script("gallery.js");
</script>
</body>
</html>
http://mikegradio.com/api/v1/podcasts/export/?tags__title=sports&sort_by=-rank&limit=50
Any help would be greatly appreciated!

Have you tried to reverse sort the collection: ( note the negative to return the collection reversed? )
comparator: function(item) {
return -item.get('pid');
}

Related

Issue with Angular don't see my data

I want that in the init to bind the model of my controller the init is called but I don't see any data what is wrong ?
Index.html
<!DOCTYPE html>
<html ng-app="I-Sign">
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta name="viewport" content="width=device-width" />
<title>Sign Language Application</title>
<link rel="stylesheet" href="scripts/jquery.mobile-1.4.5.css" />
<script type="text/javascript" charset="utf-8" src="scripts/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/angular.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/lodash.js"></script>
<script src="mainController.js"></script>
</head>
<body>
<div ng-controller="MainCtrl as ctrl" ng-init="init()">
<div id="categories">
     <ul data-role="listview" data-inset="true">
         <li ng-repeat="category in ctrl.data.categories"><a ng- click="ctrl.showWords(category)" href="#">
                 <img src="images/Can_I.png">
                 <h1>{{category.name}}</h1>
        </a>   
        </li>
</ul>
</div>
<div id="words">
    <ul data-role="listview" data-inset="true">
            
        <li ng-repeat="word in ctrl.currentWords"><a ng-click="ctrl.showMovie()" href="#">
                 <img src="images/Can_I.png">
                 <h1>{{word.name}}</h1>
        </a>                 
        </li>
</ul>
<div>
<input id="upBtn" class="ui-block-a" type="button" value="UP" ng-hide ng-click="ctrl.showCategories()">
</div>
</div>
mainController.js
var myApp = angular.module('I-Sign',[]);
myApp.controller('MainCtrl', ['$scope', function($scope) {
var self = $scope;
$scope.init = function () {
var that = this;
that.getData();
self.currentWords = [];
}
$scope.$watchCollection(function () {
//var that = this;
return self.data;
}, function () {
console.log("Changed");
});
$scope.getData = function () {
var that = this;
$.getJSON('data/database.json', function (data) {
that.data = data;
});
}
$scope.showCategories = function () {
var that = this;
$("#words").addClass("ng-hide");
$("#categories").removeClass("ng-hide");
$("#upBtn").assClass("ng-hide");
}
$scope.showWords = function (category) {
var that = this;
that.currentWords = [];
$("#categories").addClass("ng-hide");
$("#words").removeClass("ng-hide");
$("#upBtn").removeClass("ng-hide");
that.data.words.forEach(function (word) {
if (word.categoryId === category.id) {
that.currentWords.push(word);
}
});
}
}]);
Since you used jquery to get your data, you need to run a .$apply() as the code happened outside of angulars knowledge
$.getJSON('data/database.json', function (data) {
that.data = data;
$scope.$apply();
});
Alternatively you should not be using jquery at all and instead inject $http in (like you did with $scope) and use that:
$http.get('data/database.json')
.success(function(data){
that.data = data;
});
Additionally change the following:
$scope.showCategories = function () {
$scope.showCategories = true;
}
$scope.showWords = function (category) {
that.currentWords = [];
$scope.showCategories = false;
that.data.words.forEach(function (word) {
if (word.categoryId === category.id) {
that.currentWords.push(word);
}
});
}
and your html to:
<div id="categories" ng-show="showCategories">
<ul data-role="listview" data-inset="true">
<li ng-repeat="category in ctrl.data.categories">
<a ng-click="ctrl.showWords(category)" href="#">
<img src="images/Can_I.png">
<h1>{{category.name}}</h1>
</a>
</li>
</ul>
</div>
<div id="words" ng-show="!showCategories">
<ul data-role="listview" data-inset="true">
<li ng-repeat="word in ctrl.currentWords">
<a ng-click="ctrl.showMovie()" href="#">
<img src="images/Can_I.png">
<h1>{{word.name}}</h1>
</a>
</li>
</ul>
</div>
<div>
<input id="upBtn" class="ui-block-a" type="button" value="UP" ng-show="!showCategories" ng-click="ctrl.showCategories()">
</div>

Render data in ReactJS

I'm trying to learn ReactJS. In this HelloWorld script
<!DOCTYPE html>
<html>
<head>
<title>React JS Hello World</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
<script type="text/jsx">
var data=[{name: "nthhtn", text: "Sample text"}];
var DataBlock = React.createClass({
render: function() {
var entry=this.props.data.map(function (entry){
return (
<h3 name={entry.name}>
{entry.text}
</h3>
);
});
return (
<div className="data" data={this.props.data}>
<h1>Sample data block</h1>
{entry}
</div>
);
}
});
React.render(
<DataBlock data={data}/>,
document.getElementById('content')
);
</script>
</body>
</html>
I don't know why when I run script in browser, the name field in data is not displayed, only the text field is
You pass the data to getInitialState() check this fiddle https://jsfiddle.net/bs65w2hs/
var data=[{name: "nthhtn", text: "Sample text"}];
var DataBlock = React.createClass({
getInitialState: function getInitialState() {
return {
reactdata: data[0]
};
},
render: function() {
var entrydata = this.state
return <div>
<ul>
<li>name: {entrydata.reactdata.name}</li>
<li>text: {entrydata.reactdata.text}</li>
</ul>
</div>
}
});
React.render(<DataBlock />, document.getElementById('container'));
This is because you are mixing things with same variable name "entry"
render: function() {
var entryBlock=this.props.data.map(function (entry){
return (
<h3 name={entry.name}>
{entry.text}
</h3>
);
});
return (
<div className="data" data={this.props.data}>
<h1>Sample data block</h1>
{entryBlock}
</div>
);
}
Change entry to entryBlock for example (see above code). If it's not that check that there is something in entry.text.
Hope it helps.

Simple Backbone app not working

I wrote simple Backbone.js app from manual, but this does't work. Why?
It is a HTML-code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="main.css">
<script src="source/jquery.js"></script>
<script src="source/underscore.js"></script>
<script src="source/backbone.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="menu">
<ul>
<li>Start</li>
<li>Success</li>
<li>Error</li>
</ul>
</div>
<div id="start" class="block">
<div class="userplace">
<label>Enter name<input type="text" id="username"></label>
</div>
<div class="buttonplace">
<input type="button" id="button" value="Check">
</div>
</div>
<div id="error" class="block">
<p>Error - not found!</p>
</div>
<div id="success" class="block">
<p>Win!</p>
</div>
</body>
</html>
And it is a JS-code:
var Controller = Backbone.Router.extend({
routes: {
'': 'start',
'!/': 'start',
'!/error': 'error',
'!/success': 'success'
},
start: function() {
$('.block').hide();
$('#start').show();
},
error: function() {
$('.block').hide();
$('#error').show();
},
success: function() {
$('.block').hide();
$('#success').show();
},
});
var controller = new Controller();
var Start = Backbone.View.extend({
el: '#start',
events: {
'click #button': 'check'
},
check: function() {
console.log('WiN!');
if($("#username").val() == 'test') {
controller.navigate('success', true);
}
else {
controller.navigate('error', true);
}
}
});
var starter = new Start();
Backbone.history.start();
When I select point in menu, all work normal, but when I entered name into field and press button nothing happens. Event not activated. Why?
I think you're calling navigate incorrectly.
Try this:
controller.navigate('!/success', {trigger:true});
Documentation:
http://backbonejs.org/#Router-navigate

How to add mutilple dynamic items on listview?

I have two pages.The first page contains form with required fields and also a submit button(with validations).And In the second page Listview should be there. So, when i clicked on the Submit button in first page ,the entire fields should be display on the list.
I have used local storage for saving the data in the second page.It is perfect.But the data is not displaying exactly on the list.And I want to add multiple items dynamically in the firstpage,So that multiple items which are added by me can be seen in second page.
Here are my two pages code.
new.html
<!DOCTYPE HTML >
<html >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<link rel="stylesheet" href="./styles/new.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="./js-css/development-bundle/themes/start/jquery.ui.all.css">
<link rel="stylesheet" media="screen" type="text/css" href="js-css/development-bundle/themes/base/jquery.ui.datepicker.css" />
<script type="text/javascript" src="js-css/development-bundle/jquery-1.10.2.js"> </script>
<script type="text/javascript" src="js-css/development-bundle/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="js-css/development-bundle/ui/jquery.ui.datepicker.js"></script>
<script type="text/javascript">
$(function(){
var pickerOpts = {
appendText: "",
defaultDate: "+5",
showOtherMonths: true,
dateFormat: "dd/mm/yy",
};
$("#strtd").datepicker({
minDate: 0
});
$("#sub").datepicker({
maxDate: new Date,
minDate: new Date(2007, 6, 12)
});
$('#strtd').focus(function() {
this.blur();
});
$('#sub').focus(function() {
this.blur();
});
});
function back() {
window.open("file:///android_asset/www/index.html");
}
//form validation
function validateForm() {
localStorage.setItem("RecordName", document.myForm.RecordName.value);
localStorage.setItem("StartedDate", document.myForm.StartedDate.value);
localStorage.setItem("SubmitedDate", document.myForm.SubmitedDate.value);
var x = document.forms["myForm"]["name"].value;
var y= document.forms["myForm"]["strtd"].value;
var z= document.forms["myForm"]["sub"].value;
if (x==null || x=="") {
alert("Record name must be filled out");
return false;
}
else if (y==null || y=="") {
alert("Started Date must be filled out");
return false;
}
else if (z==null || z=="") {
alert("Submitted Date must be filled out");
return false;
}
else {
alert("New Record Created");
}
}
</script>
</head>
<body>
<form name="myForm" id="form" type="get" onsubmit="return validateForm()" action="lead.html">
<div id="top"> New Record</div>
<div>
<h5>Record Name <input type="text" name="RecordName" id="name"></h5>
</div>
<div >
<h5>Started Date <input id="strtd" type="text" name="StartedDate"></h5>
</div>
<div>
<h5>Submitted Date <input id="sub" type="text" name="SubmitedDate"></h5>
</div><br>
<div align="center">
<input type="submit" id="submit" value="Submit" >
</div>
</form>
<div align="center">
<button id="cancel" onclick="back()">Back</button>
</div>
</body>
</html>
and my second page lead.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./styles/lead.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"> </script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
<script>
function mylead1()
{
window.open("file:///android_asset/www/editlead.html");
}
function mylead2()
{
window.open("file:///android_asset/www/editlead.html");
}
function mylead3()
{
window.open("file:///android_asset/www/editlead.html");
}
function onBackKey()
{
window.open("file:///android_asset/www/new.html");
}
</script>
</head>
<body id="lead">
<div id="top" align="center" > Leads </div>
<img id="plus" src="./images/plus.png" onclick="onBackKey()" >
<div data-role="page" style="margin-top:100px;" >
<div data-role="main" id="content" style="min-height:60px;">
<ul id="unorder" data-role="listview" data-theme="a" data-dividertheme="b">
<li id="list" data-role="list-divider">
<label id="label1" > </label><br>
<label id="label2"></label><br>
<label id="label3"></label>
<img id="arrow" src="./images/Arrow#2x.png" style="margin-left:250px" onclick="mylead1()">
</li>
</ul>
</div>
</div>
</body>
<script>
//local storage
document.getElementById("label1").innerHTML= localStorage.getItem("RecordName");
document.getElementById("label2").innerHTML= localStorage.getItem("StartedDate");
document.getElementById("label3").innerHTML= localStorage.getItem("SubmitedDate");
</script>
<script>
$("#submit").click( function() {
$("ul").append("<li></li>").listview("refresh");
li.text("#label1");
$("#unorder").append(li);
$("#unorder").listview("refresh");
})
</script>
</html>
My requirement is to get the added data(in new.html) dynamically on second page(lead.html)
`Please guide me for resolving it.Thanks :)
local storage is working fine , so m not focusing on it.
Here concern is displaying all data from first page in second that too in list format
this is the most simplest way to do this,
ON FIRST PAGE
on form submit suppose you are calling one function name redirect
function redirect()
{
var form = $("form[name='myForm']");
form_data = form.serialize();
window.location = "secondpage.html?"+form_data // eg: secondpage.html?single=Single2&multiple=Multiple&multiple=Multiple3&radio=radio1
}
ON SECOND PAGE
function which will parse url and give parameters as objects
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
var url = window.location.href ; //'www.example.com?ferko=suska&ee=huu';
var parameters = $.parseParams( url.split('?')[1] || '' ); // object { ferko: 'suska', ee: 'huu' }
var li='';
$.each( parameters, function( key, value ) {
// write html code
li += "<li>"+value+"</li>"
});
$("ul").html(li);
<ul>
</ul>

backbone.js routing issue

I am very new to js and backbone.js, and I assure you I have searched extensively in docs and on here. I am trying to build a simple site that displays photos (eventually other things) and I want to be able to click a photo to see a different 'page' with another view/template. I cant seem to get this to work and now I am getting a "Uncaught TypeError: Cannot call method 'get' of undefined" in my router's photoById method. Code below... THANKS!
//------ main.js
var photoListTemplate = Handlebars.compile($('#photo-list-template').html());
var photoTemplate = Handlebars.compile($('#photo-template').html());
var navTemplate = Handlebars.compile($('#navigation-template').html());
var Photo = Backbone.Model.extend({
defaults: function() {
return {
};
},
initialize: function(options) {
}
});
var PhotoCollection = Backbone.Collection.extend({
model: Photo
});
var PhotoView = Backbone.View.extend({
events: {
},
//tagName: 'td',
className: 'photo',
template: photoTemplate,
initialize: function(options) {
_.bindAll(this, 'render');
this.model.on('change', this.render);
},
render: function() {
$(this.el).empty().append(this.template(this.model.toJSON()));
return this;
}
});
var PhotoCollectionView = Backbone.View.extend({
tagName: 'table',
className: 'photo-list',
template: photoListTemplate,
events: {
},
initialize: function(options) {
this.collection.on('add remove', this.render, this);
},
render: function() {
$(this.el).empty();
this.collection.each(function(photo){
$(this.el).append(new PhotoView({model: photo}).render().el);
}, this);
return this;
}
});
var PhotoRouter = Backbone.Router.extend({
routes: {
"": "list",
"photo/:id": "photoById"
},
initialize: function(options) {
},
allPhotos: function() {
this.photoList = new PhotoCollection();
this.photoCollectionView = new PhotoCollectionView({collection: this.photoList});
this.photList.fetch();
$('#content').empty().append(this.photoCollectionView.render().el);
},
photoById: function(id){
this.photo = this.photoList.get(id);
this.photoView = new PhotoView({model: this.photo});
$('#content').empty().append(this.photoView.render().el);
}
});
var photos = null;
$.getJSON('http://localhost:3000/photos.json', function(response){
photos = new PhotoCollection(response);
$('#container').append(new PhotoCollectionView({collection: photos}).render().el);
var photoRouter = new PhotoRouter();
Backbone.history.start();
});
/----- index.html
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please upgrade your browser or activate Google Chrome Frame to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<!-- <p>Replace Me! Replace Me!</p> -->
<div class='container' id='container'>
</div>
<script type="text/x-handlebars-template" id='navigation-template'>
<div class='navbar'>
<div class='navbar-inner'>
<a class='brand' href=#>ohayon</a>
<ul class='nav'>
</ul>
</div>
</div>
</script>
<script type="text/x-handlebars-template" id='photo-template'>
<div class='lead'>
<a href='#photo/{{id}}'>{{name}}</a>
<img src='http://localhost:3000{{image.url}}' height='200' width='200'>
</div>
</script>
<script type="text/x-handlebars-template" id='photo-list-template'>
<div class='lead'>
<a href='#photos/{{id}}'>{{name}}</a>
<img src='http://localhost:3000{{image.url}}'>
</div>
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<!-- If we want Boostrap components -->
<script src="js/bootstrap.js"></script>
<!-- Templating with Handlebars -->
<script src="js/handlebars.js"></script>
<!-- We Need Underscore.js -->
<script src="js/underscore.js"></script>
<!-- And Finally Backbone -->
<script src="js/backbone.js"></script>
<!-- Your Code goes here -->
<script src="js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
The way you've got it coded, there's no guarantee this.photoList will have been created by the time you attempt to use it in photoById. You might want to create it in the router's init function:
initialize: function(options) {
this.photoList = photos;
},
Also remove a few lines from allPhotos -- you don't want to re-create PhotoCollection or call fetch, since it was already created and populated in the first step of your app. Should look like this:
allPhotos: function() {
this.photoCollectionView = new PhotoCollectionView({collection: this.photoList});
$('#content').empty().append(this.photoCollectionView.render().el);
},
(One other problem, you're using container sometimes and content others.)
It's running here. (I used some dummy data to test with.)

Categories

Resources