I\'ve got an application receiving some data through AJAX-call. After that, received data binds to DOM-elements using knockout.js library. I\'d like to use boostrap
You can create custom dataBinding to make that element popover. Check this jsfiddle demo
ko.bindingHandlers.bootstrapPopover = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var options = ko.utils.unwrapObservable(valueAccessor());
var defaultOptions = {};
options = $.extend(true, {}, defaultOptions, options);
$(element).popover(options);
}
};
var viewModel = {
items: ko.observableArray([{
"id": 1,
"title": "title-1",
"info": "info-1"},
{
"id": 2,
"title": "title-2",
"info": "info-2"},
{
"id": 3,
"title": "title-3",
"info": "info-3"}])
}
ko.applyBindings(viewModel);
And html
<div class="container">
<div class="hero-unit">
<table class="table table-condensed" data-bind="foreach: items">
<tr>
<td><b data-bind="text: $data.id"></b></td>
<td data-bind="text: $data.title"></td>
<td><a href="#" data-bind="bootstrapPopover : {content : $data.info }">Info</a></td>
</tr>
</table>
</div>
</div>
Here is a complete working example with array of objects, I changed the ko.applyBindings()
to ko.applyBindingsToDescendants
to include the binding context $root and $parent when we would like to associate a button for example to a function in a root viewModel.
$(element).click(function() {
$(this).popover('toggle');
var thePopover = document.getElementById(attribute.id+"-popover");
childBindingContext = bindingContext.createChildContext(viewModel);
ko.applyBindingsToDescendants(childBindingContext, thePopover);
});
Take a look @ http://jsfiddle.net/mounir/Mv3nP/6/
"According to the latest bootstrap documentation, implicit call of something like $('.popover').popover() isn't required, however, it's not working."
I can't find anywhere in the docs that states that. In fact, they state quite the opposite. Namely, Twitter Bootstrap does not automatically initialize popovers or tooltips on a page. From the docs:
For performance reasons, the Tooltip and Popover data-apis are opt in. If you would like to use them just specify a selector option.
In order to "opt in", as they say, you would attach the Popover object to an element which contains all the popovers which might appear on the page. Here's one way of doing it:
$('body').popover({selector: '[rel="popover"]'});
I believe the performance considerations originally in mind came from the fact that prior to 2.1, the Popover plugin was by default triggered by mouseenter and mouseleave events, which are certainly not something you want to be constantly processing for an entire page.
Since 2.1, the default is now click, which shouldn't pose any performances issues. Nevertheless, if you can determine an element farther down the DOM than body
to which to attach the Popover object, that is always preferred. However, depending on where you are displaying the AJAX content, body
might be your best bet.