JSFiddle - React, Tailwind, and code Playground
HTML
<div id="Corp_Module_toDoItemsList">
<h2>To-Do Items</h2>
<div id="Corp_Module_toDoItems" data-bind="foreach: {data: viewModel.ToDoItems, as:'toDoItem'}">
<span class="Corp_Module_toDoItem" id="933e3328-8980-46f9-b89a-6fbce63fb36a" data-bind="text: Task">Complete the to-do module</span>
</div>
<div id="Corp_Module_toDoItems_Ftr">
<input type="text" data-bind="value:newTask, valueUpdate: 'afterkeydown'" Placeholder="New Task" />
<button id="Corp_Module_toDoAdd" type="button" data-bind="click: AddToDoItem">Add ToDo</button>
</div>
</div>
CSS
.Corp_Module_toDoItem { display: block; margin:2px;padding:3px;border:1px gray solid; }
JavaScript
//viewModel for toDoItems in knockout
function toDoItemsViewModel(initArray, onArrayUpdate) {
var self = this;
//init array to values passed in from html node list
self.ToDoItems = ko.observableArray(initArray);
//subscribe to changes of array by calling the onArrayUpdate function
self.ToDoItems.subscribe(function(changes) {
onArrayUpdate(changes);
}, null, "arrayChange");
//newTask property provides binding to the New Task textbox
self.newTask = ko.observable("");
self.AddToDoItem = function () {
//if not blank, push to array as new item
if (self.newTask != "") {
self.ToDoItems.push(new toDoItemModel("", self.newTask()));
self.newTask("");//clear text box
}
};
}
function toDoItemModel(toDoId, task) {
var self = this;
self.Task = task;
self.ToDoId = toDoId;
}
var existingToDoItems = [];
//demo only : use the existing html to populate the array for an example
jQuery('#Corp_Module_toDoItems').children('span').each(function (index) {
var toDoItem = new toDoItemModel(this.id, this.innerText);
existingToDoItems[existingToDoItems.length] = toDoItem;
});
//init viewModel and bind with onArrayUpdate function
viewModel = new toDoItemsViewModel(existingToDoItems, onArrayUpdate);
ko.applyBindings(viewModel);
//callback for array updates
function onArrayUpdate (changes) {
changes.forEach(function(change) {
if (change.status === 'added' || change.status === 'deleted') {
console.log("Added or removed! The added/removed element is:", change.value);
}
});
}