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>
<select id='view-contacts'></select>
<br /><button id='reset'>click to reset</button>
<br /><button id='add'>click to add</button>
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.on('add', this.model_added, this);
},
model_added: function(){
log('A new model has been created');
}
});
var ContactsView = Backbone.View.extend({
initialize: function(){
log("ContactsView initialize");
this.collection.on('reset', this.populate, this);
this.collection.on('add', this.populate, this);
// do an initial render which will reflect the state of your collection
this.populate();
},
// 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(){
log('populate the select with collection data');
this.$el.empty();
this.collection.each(function(model){
this.$el.append("<option>"+model.get("name")+"</option>");
},this);
},
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:...