A Pen by Kevin Colten on CodePen.
Created
November 1, 2015 03:53
-
-
Save kevincolten/29f2e59c87dfefe5c71f to your computer and use it in GitHub Desktop.
Backbone App
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="person-list"></div> | |
<div id="person-detail"></div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var AppRouter = Backbone.Router.extend({ | |
initialize: function() { | |
Backbone.history.start(); | |
}, | |
routes: { | |
'': 'index' | |
}, | |
index: function() { | |
var people = new PeopleCollection(); | |
people.fetch() | |
var peopleListView = new PeopleListView({ | |
collection: people | |
}); | |
$('#person-list').html(peopleListView.$el); | |
peopleListView.render(); | |
} | |
}); | |
var PersonModel = Backbone.Model.extend({ | |
urlRoot: 'https://reqres-api.herokuapp.com/api/users', | |
idAttribute: 'id', | |
}); | |
var PeopleCollection = Backbone.Collection.extend({ | |
url: 'https://reqres-api.herokuapp.com/api/users', | |
model: PersonModel | |
}); | |
var PeopleListView = Backbone.View.extend({ | |
el: '<ul></ul>', | |
initialize: function() { | |
this.listenTo(this.collection, 'update', this.render); | |
}, | |
render: function() { | |
var that = this; | |
that.$el.html(''); | |
this.collection.each(function(person) { | |
var personItemView = new PersonItemView({ | |
model: person | |
}); | |
that.$el.append(personItemView.$el); | |
personItemView.render(); | |
}); | |
return this; | |
} | |
}); | |
var PersonItemView = Backbone.View.extend({ | |
template: _.template('<a href="#"><%= user.get("first_name") %></a>'), | |
el: '<li></li>', | |
events: { | |
'click a': 'viewPersonDetail' | |
}, | |
viewPersonDetail: function(e) { | |
e.preventDefault(); | |
this.model.fetch(); | |
var personDetailView = new PersonDetailView({ | |
model: this.model | |
}); | |
$('#person-detail').html(personDetailView.$el); | |
personDetailView.render(); | |
}, | |
render: function() { | |
this.$el.html(this.template({ | |
user: this.model | |
})); | |
return this; | |
} | |
}); | |
var PersonDetailView = Backbone.View.extend({ | |
template: _.template('<img src="<%= user.get("avatar") %>">'), | |
initialize: function() { | |
this.listenTo(this.model, 'sync', this.render); | |
}, | |
render: function() { | |
this.$el.html(this.template({ | |
user: this.model | |
})); | |
return this; | |
} | |
}); | |
new AppRouter(); |
A Pen by Kevin Colten on CodePen.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment