JSFiddle - React, Tailwind, and code Playground
by Mohammed Ismail Ansari
HTML
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
<div id="display-div" data-bind="foreach: listOfPeople">
<span data-bind="text: firstName"></span>
<span data-bind="text: lastName"></span>
<br />
</div>
<input id="firstName" type="text"></input>
<input id="lastName" type="text"></input>
<button data-bind="click: addPerson">Add</button>
CSS
body
{
font-family: Arial;
}
JavaScript
// Observable Arrays
// Our viewmodel with observables
function viewmodel() {
self = this;
// Observable array
this.listOfPeople = ko.observableArray([
{ firstName: "John", lastName: "Shepard" },
{ firstName: "Kaidan", lastName: "Alenko" },
{ firstName: "Ashley", lastName: "Williams" }
]);
// Method to add a person
this.addPerson = function (){
var newFirstName = $("#firstName").val();
var newLastName = $("#lastName").val();
self.listOfPeople.push({
firstName: newFirstName,
lastName: newLastName
});
};
}
// Runs at document load
$(document).ready(function(){
// Create an instance of the viewmodel
var myViewmodel = new viewmodel();
// Bind the instance to the view
ko.applyBindings(myViewmodel);
});