Knockoutjs with AutoComplete
by smichelotti
HTML
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-1.3.0beta.debug.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css">
<input type="text" id="tags"/>
<ul id="tagList">
<!-- ko foreach: tags -->
<li>
<span data-bind="text: label"></span>
<button class="remove-item">Remove</button>
</li>
<!-- /ko -->
</ul>
JavaScript
var fakeData = [{ Id: 1, label: "Tag1" },
{ Id: 2, label: "Tag2" },
{ Id: 3, label: "Tag3" }];
$(function() {
var viewModel = {
tags: ko.observableArray([{ Id: 1, label: "Tag0" }])
};
$(".remove-item").live("click", function() {
viewModel.tags.remove(ko.dataFor(this));
});
$("#tags").autocomplete({
source: fakeData,
select: function(event, ui){
event.preventDefault();
viewModel.tags.push(ui.item);
$(this).val("");
}
});
ko.applyBindings(viewModel);
});