<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-debug.js"></script>
<input type="text" placeholder="Add Tags" data-bind="value: tagToAdd, valueUpdate: 'afterkeydown', executeOnEnter: addTag"/>
<button data-bind="{click: addTag}">+</button>
<ul data-bind="foreach: tags">
<li data-bind='click: $parent.selectTag'>
<span data-bind="text: name"></span>
<a class="tag-edit">Edit</a>
<a class="tag-delete">Delete</a>
</li>
</ul>
<!--Setting this div's context with selectedTag; which is a child of viewModel. So we can use name property, which although is not present in ViewModel object but is present in selectedTag-->
<div id="tagDialog" data-bind="with: selectedTag">
Tag Name:
<input type="text" data-bind="value: name"/>
</div>
JavaScript
$(function() {
var data=[
new dataItem("Pratik"),
new dataItem("Varun"),
new dataItem("Pradeep")
];
function dataItem (Name) {
return {
name: ko.observable(Name)
};
}
//Since we are data-binding the name property of a tag we need to make sure that name is alos ko observable
var viewModel = {
tags: ko.observableArray(data),
tagToAdd: ko.observable(""),
selectedTag: ko.observable(""),
addTag: function() {
this.tags.push({name: this.tagToAdd()});
this.tagToAdd('');
},
selectTag: function() {
viewModel.selectedTag(this);
//alert(viewModel.selectedTag().name);
}
};
$(document).on('click', '.tag-edit', function() {
$('#tagDialog').dialog({
buttons: {
Save: function() { $(this).dialog('close'); },
Close: function() { $(this).dialog('close'); }
}
});
});
$(document).on('click', '.tag-delete', function() {
var itemToRemove = ko.dataFor(this);
viewModel.tags.remove(itemToRemove);
});
ko.bindingHandlers.executeOnEnter = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
$(element).keypress(function(event) {
var keyCode = (event.which?event.which:event.keyCode);
if (keyCode === 13) {
value.call(viewModel); //value is the function, so we could have directly called value but we are using JS function call and passing viewModel, because we want the this object inside value function to point to the view Model
return false;
}
return true;
});
}
};
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.