var model= {//this code is injected into the page on the server or retrieved via ajax
items: [
{ id:"21EC2020-3AEA-1069-A2DD-08002B30309E", c1: "d", c2: "210", c3: "1005", isDeleted:false},
{ id:"C3EC2020-3AEA-1069-A2DD-08002B303094", c1: "z", c2: "1", c3: "205", isDeleted:false},
{ id:"DDEC2020-3AEA-1069-A2DD-08002B30309D", c1: "a", c2: "20", c3: "2005", isDeleted:false}
]
};
var viewModel = ko.mapping.fromJS(model);//create a knockout viewModel
viewModel.visibleItems = ko.dependentObservable({
read: function readVisibleItems(){
//note the parens after Items because its an observableArray
return $.map(viewModel.items(), function(item){
//note the parens after isDeleted because its observable
return !item.isDeleted() ? item : null;
});
},
owner:viewModel
});
//add actions to your model
viewModel.actions = {
addItem:function(){
//fromJS maps turns all properties into observables
var newItem = ko.mapping.fromJS({id:null, c1: "", c2: "", c3: "", isDeleted:false})
viewModel.items.push(newItem);
},
deleteItem:function(item){
var deleteIndex;
//ensure a visible line always exists
if(viewModel.visibleItems().length == 1){
viewModel.actions.addItem();
}
//note items that were sent down from server have isExisting set to true
//and must be deleted at the server, however items that were created locally
//can be deleted locally
if(!item.id()){//locally create items don't have an id
deletedIndex = viewModel.items.indexOf(item);
//assign new array to items, minus the deleted item
viewModel.items($.map(viewModel.items(), function (element, index) {
return index === deletedIndex ? null : element;
}));
}
else{
item.isDeleted(true);
}
}
};
//bind viewModel to...
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.