Skip to content

Instantly share code, notes, and snippets.

@nathggns
Created June 25, 2014 14:06
Show Gist options
  • Save nathggns/0874a3558d1f107e3922 to your computer and use it in GitHub Desktop.
Save nathggns/0874a3558d1f107e3922 to your computer and use it in GitHub Desktop.
Knockout (2.3+) binding for clamp
define(['knockout', 'clamp'], function(ko, $clamp) {
'use strict';
var textKey = 'originalClampText';
ko.bindingHandlers.clamp = {
update: function(element, valueAccessor, allBindings) {
var defaultText;
// Deal with differences in API from 2.3 - 3.0+
if (typeof allBindings.get === 'function') {
defaultText = allBindings.get('text');
} else {
defaultText = allBindings().text;
}
// Get the text that we want to work on, as $clamp is destructive
// we have to fix the element before we call it for when the
// binding changes.
var text = defaultText ||
ko.utils.domData.get(element, textKey) ||
element.innerHTML;
// Store the text againt the dom element in case we're not using
// an observable
ko.utils.domData.set(element, textKey, text);
// Fix the element to use the full text, rather than the clamped
// text
element.innerHTML = text;
$clamp(element, { clamp : ko.unwrap(valueAccessor()) });
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment