JSFiddle - React, Tailwind, and code Playground
by knunery
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<div id="simplelist_app" class='liveExample'>
New item:
<input id="new-item" data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />
<button data-bind='enable: itemToAdd().length > 0' id='add-item' type='submit'>Add</button>
<p>Your items:</p>
<div>
<select id='simplelist' multiple='multiple' width='50'></select>
</div>
</div>
CSS
body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; }
JavaScript
//Simple List
var SimpleItemModel = Backbone.Model.extend({
defaults: {
value: 'item XXX'
}
});
var SimpleList = Backbone.Collection.extend({
model: SimpleItemModel
});
var ItemView = Backbone.View.extend({
tagName: 'option',
template: _.template('<%= value %>'),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var SimpleListView = Backbone.View.extend({
initialize: function() {
this.collection.on('add', this.addOne, this);
},
el: $('#simplelist_app'),
events: {
"click #add-item": "addItem"
},
render: function() {
this.collection.forEach(this.addOne, this);
},
addOne: function(model) {
var itemView = new ItemView({
model: model
});
itemView.render();
this.$el.find('#simplelist').append(itemView.el);
},
addItem: function() {
console.log('addItem');
var newItem = $("#new-item");
var itemValue = newItem.val();
if(!!itemValue)
{
newItem.val('');
this.collection.add(new SimpleItemModel({
value: itemValue
}));
}
}
});
var simpleList = new SimpleList();
/*
// for debugging... adds one item to list initially...
simpleList.add(new SimpleItemModel({
value: 'test fff'
}));
*/
var simpleListView = new SimpleListView({
collection: simpleList
});
simpleListView.render();
$("#simplelist_container").html(simpleListView.el);
/*
// knockout code
var viewModel = {};
viewModel.items = ko.observableArray(["Alpha", "Beta", "Gamma"]);
viewModel.itemToAdd = ko.observable("");
viewModel.addItem = function() {
if (viewModel.itemToAdd() != "") {
viewModel.items.push(viewModel.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
viewModel.itemToAdd(""); // Clears the text box, because it's bound...