function Task(name) {
this.name = ko.observable(name);
}
var viewModel = {
tasks: ko.observableArray([
new Task("Get dog food"),
new Task("Mow lawn"),
new Task("Fix car"),
new Task("Fix fence"),
new Task("Walk dog"),
new Task("Read book")
]),
selectedTask: ko.observable(),
selectTask: function(task) {
this.selectedTask(task);
},
addTask: function() {
var task = new Task("new");
this.selectedTask(task);
this.tasks.push(task);
}
};
//connect items with observableArrays
ko.bindingHandlers.sortableList = {
init: function(element, valueAccessor) {
var list = valueAccessor();
$(element).sortable({
update: function(event, ui) {
//retrieve our actual data item
var item = ui.item.tmplItem().data;
//figure out its new position
var position = ko.utils.arrayIndexOf(ui.item.parent().children(), ui.item[0]);
//remove the item and add it back in the right spot
if (position >= 0) {
list.remove(item);
list.splice(position, 0, item);
}
ui.item.remove();
}
});
}
};
//control visibility, give element focus, and select the contents (in order)
ko.bindingHandlers.visibleAndSelect = {
update: function(element, valueAccessor) {
ko.bindingHandlers.visible.update(element, valueAccessor);
if (valueAccessor()) {
setTimeout(function() {
$(element).focus().select();
}, 0); //new tasks are not in DOM yet
}
}
}
ko.applyBindings(viewModel);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.