JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
JavaScript
function log(m) {
$("body").append("<p>"+m+"</p>");
};
var Contact = Backbone.Model.extend({
});
var Contacts = Backbone.Collection.extend({
model: Contact,
initialize: function(){
log("Contacts initialize");
this.trigger('init');
this.on('add', this.model_added, this);
},
model_added: function(){
log('A new model has been created so trigger an event for the View to update the <select> menu');
}
});
var ContactsView = Backbone.View.extend({
initialize: function(){
log("ContactsView initialize");
this.collection.on('init', this.populate, this);
log('get initial model data and populate the select menu?');
},
// built-in 'events' management only applies to DOM elements (as this is a 'View' after all)
// other custom events triggered are handled via 'this.on' within the initialize method
// because of this we have to use 'this.on' within a 'Collection'
events: {
'change select': 'displaySelected'
},
populate: function(){
console.log('populate the <select> with initial Model data');
},
displaySelected: function (event) {
console.log('get model data and display selected user', event);
}
});
var manager = new Contact({
id: "id_manager",
name: 'Mark McDonnell',
age: 30
});
var developer = new Contact({
id: "id_developer",
name: 'Ashley Banks',
age: 23
});
log("create contacts");
var contacts = new Contacts([manager, developer]);
log("create contacts view");
var contacts_view = new ContactsView({
el: $('#view-contacts'),
collection: contacts // pass in the Collection into this View
});