JSFiddle - React, Tailwind, and code Playground
by gurkavcu
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.0/css/bootstrap.min.css">
<!doctype html>
<html>
<body>
<br><br><br>
<div data-bind="foreach: items">
<span data-bind="text: label"></span>
<input type="checkbox" data-bind="checked: required" />
<button data-bind="popover: {template: 'settingsPopover', trigger: 'click'}">settings</button><br>
</div>
<script type="text/html" id="settingsPopover">
<h4><span class="icon-cog"> </span> Attributes</h4>
<label>Label</label>
<input type="text" data-bind="value: label, valueUpdate:'afterkeydown'" />
<label class="checkbox">
<input type="checkbox" data-bind="checked: required" /> Required
</label>
<ul data-bind="foreach: options">
<li data-bind="text: $data"></li>
</ul>
</script>
</body>
</html>
JavaScript
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
function guid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
// Bind Twitter Popover
ko.bindingHandlers.popover = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var $element = $(element);
// read popover options
var popoverBindingValues = ko.utils.unwrapObservable(valueAccessor());
// set popover title
var popoverTitle = popoverBindingValues.title;
// set popover template id
var tmplId = popoverBindingValues.template;
// set popover trigger
var trigger = popoverBindingValues.trigger;
// get template html
var tmplHtml = $('#' + tmplId).html();
// create unique identifier to bind to
var uuid = guid();
var domId = "ko-bs-popover-" + uuid;
// create correct binding context
var childBindingContext = bindingContext.createChildContext(viewModel);
// create DOM object to use for popover content
var tmplDom = $('<div/>', {
"class" : "ko-popover",
"id" : domId
}).html(tmplHtml);
// set content options
// bind popover to element click
$element.bind(trigger, function (e) {
ko.applyBindingsToNode( tmplDom[0], {template : { name :'settingsPopover', data : viewModel}});
options = {
content: tmplDom[0].outerHTML,
title: popoverTitle
};
// Need to copy this, otherwise all the popups end up with the value of the last item
var popoverOptions = $.extend({}, ko.bindingHandlers.popover.options, options);
$(this).popover(popoverOptions).popover('show');
// }
});
// Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
return { controlsDescendantBindings: true };
},
options:...