Created
March 11, 2014 23:24
-
-
Save kfatehi/9497191 to your computer and use it in GitHub Desktop.
basic backbone.js usage
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
var data = { | |
people: [ | |
{ | |
"id": "1", | |
"img": "1-dan.jpg", | |
"name": "Dan" | |
}, | |
{ | |
"id": "2", | |
"img": "2-ron.jpg", | |
"name": "Ron" | |
} | |
] | |
}; | |
window.App = { | |
Models: {}, | |
Collections: {}, | |
Views: {}, | |
Routers: {} | |
}; | |
App.Models.Person = Backbone.Model.extend({}); | |
App.Collections.People = Backbone.Collection.extend({ | |
model: App.Models.Person | |
}); | |
App.Views.Person = Backbone.View.extend({ | |
tagName: 'li', | |
events: { | |
'click': 'showName' | |
}, | |
initialize: function(options) { | |
this.model = options.model; | |
}, | |
showName: function() { | |
alert(this.model.get('name')); | |
}, | |
render: function() { | |
this.$el.html(''); | |
// <img src='"+this.model.get('img')+"'/> | |
var item = $("<a href='#'>"+this.model.get('img')+"</a>"); | |
this.$el.append(item); | |
return this; | |
} | |
}); | |
App.Views.People = Backbone.View.extend({ | |
tagName: 'ul', | |
className: 'list', | |
attributes: { | |
'data-appbuilder-object':'list' | |
}, | |
initialize: function(options) { | |
this.collection = options.collection; | |
}, | |
render: function() { | |
this.$el.html(''); | |
this.collection.each(function(person) { | |
this.renderPerson(person); | |
}.bind(this)); | |
return this; | |
}, | |
renderPerson: function(person) { | |
var view = new App.Views.Person({model: person}); | |
this.$el.append(view.render().el); | |
} | |
}); | |
App.init = function() { | |
var people = new App.Collections.People(data.people); | |
var view = new App.Views.People({collection: people}); | |
$('.people').append(view.render().$el); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment