Created
January 3, 2014 21:06
-
-
Save seiyria/8246602 to your computer and use it in GitHub Desktop.
A tooltip binding for knockout/bootstrap to get data from a remote source.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Option Parameters: | |
url - the URL that will be sending back the tooltip data (required) | |
loadingText - the placeholder text during the loading process | |
getDelay - the delay between when the loading text is shown and when the GET request is sent | |
emptyText - the text that is shown if there was an empty or invalid (404) response from the server | |
cache - if this is true, the response will be cached and will not be re-requested | |
options - these are passed to the bootstrap base tooltip call | |
*/ | |
ko.bindingHandlers.remoteTooltip = { | |
init: function(element, valueAccessor) { | |
var local = ko.utils.unwrapObservable(valueAccessor()), | |
options = {}; | |
options.options = {}; | |
options.cache = true; | |
ko.utils.extend(options, local); | |
if(options.hasOwnProperty('loadingText')) | |
options.options.title = options.loadingText; | |
$(element).tooltip(options.options); | |
var determineTooltipText = function(data) { | |
if(!data && options.emptyText) | |
data = options.emptyText; | |
if(options.cache) | |
$(element).attr('data-cache', true); | |
$(element).tooltip('hide') | |
.attr('data-original-title', data) | |
.tooltip('fixTitle') | |
.tooltip('show'); | |
}; | |
$(element).hover(function(e) { | |
if($(element).data('cache')) | |
return; | |
var delay = options.hasOwnProperty('getDelay') ? options.getDelay : 0; | |
setTimeout(function() { | |
$.get(options.url, {}, function(data, status, jqXHR) { | |
determineTooltipText(data); | |
}).fail(function() { | |
determineTooltipText(); | |
}); | |
}, delay); | |
}); | |
ko.utils.domNodeDisposal.addDisposeCallback(element, function() { | |
$(element).tooltip("destroy"); | |
}); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<span data-bind=" | |
remoteTooltip: { | |
url: './test.txt', | |
loadingText: 'Loading...', | |
getDelay: 1500, | |
emptyText: 'No data available.', | |
cache: true, | |
options: { | |
delay: { show: 50, hide: 10 } | |
} | |
} | |
"></span> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment