Fiddle: http://jsfiddle.net/LkqTU/9399/
Code:
var ViewModel = function (first, last) { var self = this; self.showIcon = ko.observable(false); self.triggerIcon = function () { self.showIcon(true); }; }; $('.card-delete-button').tooltip({ 'placement': 'top', 'title': 'Text' }); ko.applyBindings(new ViewModel("Planet", "Earth"));
For some reason the tooltip isn't showing up for the '.card-delete-button'. I think it's because that DOM element isn't available until the triggerIcon function is hit. But in application, I have to bind these tooltips to a lot of different elements and would prefer to do it once, in one place, instead of sticking the binding into the triggerIcon function. how can this be achieved?
Your best bet in a situation like this is to create a custom binding that you can use to place tooltips anywhere in the markup.
Here is one implementation of a tooltip binding:
ko.bindingHandlers.tooltip = { init: function(element, valueAccessor) { var local = ko.utils.unwrapObservable(valueAccessor()), options = {}; ko.utils.extend(options, ko.bindingHandlers.tooltip.options); ko.utils.extend(options, local); $(element).tooltip(options); ko.utils.domNodeDisposal.addDisposeCallback(element, function() { $(element).tooltip("destroy"); }); }, options: { placement: "right", trigger: "click" } };
You would then use this binding on your page like:
<input data-bind="value: name, tooltip: { title: help, trigger: 'hover' }" />
You can set options globally and then override them with whatever you pass into the binding.
When you get into templating and control-flow scenarios, using a custom binding really helps, because it will automatically get initialized (and cleaned up) at the right time without needing to manually know when to call code.
Here is a sample: http://jsfiddle.net/rniemeyer/BF5yW/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With