Created
February 26, 2013 23:58
-
-
Save osbornm/5043549 to your computer and use it in GitHub Desktop.
Knockout Widget Binding - Why does Knockout not have one of these built in?
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
function _getWidgetBindings(element, valueAccessor, allBindingsAccessor) { | |
var value = valueAccessor(), | |
myBinding = ko.utils.unwrapObservable(value), | |
allBindings = allBindingsAccessor(); | |
if (typeof (myBinding) === 'string') { | |
myBinding = { 'name': myBinding }; | |
} | |
var widgetName = myBinding.name, | |
widgetOptions = myBinding.options; | |
// Sanity check: can't directly check that it's truly a _widget_, but | |
// can at least verify that it's a defined function on jQuery: | |
if (typeof $.fn[widgetName] !== 'function') { | |
throw new Error("widget binding doesn't recognize '" + widgetName + "' as jQuery UI widget"); | |
} | |
// Sanity check: don't confuse KO's 'options' binding with jqueryui binding's 'options' property | |
if (allBindings.options && !widgetOptions && element.tagName !== 'SELECT') { | |
throw new Error("widget binding options should be specified like this:\ndata-bind='widget: {name:\"" + widgetName + "\", options:{...} }'"); | |
} | |
return { | |
widgetName: widgetName, | |
widgetOptions: widgetOptions | |
}; | |
} | |
// Knockout binding for jQuery UI widgets | |
// | |
// Examples: | |
// <input type="submit" value="OK" data-bind='widget: "button"' /> | |
// <input id='search' data-bind='widget: { name: "autocomplete", options: { source: searchCompletions(), delay: 500 } }, value: searchString' /> | |
ko.bindingHandlers.widget = { | |
update: function (element, valueAccessor, allBindingsAccessor) { | |
var widgetBindings = _getWidgetBindings(element, valueAccessor, allBindingsAccessor); | |
$(element)[widgetBindings.widgetName](widgetBindings.widgetOptions); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@skoon think of a tooltip widget like in bootstrap, If a new row is added I want the tooltip to get wired up for that row. How would you bind something that isn't even in the DOM yet?