Skip to content

Instantly share code, notes, and snippets.

@romeshniriella
Last active August 29, 2015 14:17
Show Gist options
  • Save romeshniriella/ca0fcbb25c7f0bea8e03 to your computer and use it in GitHub Desktop.
Save romeshniriella/ca0fcbb25c7f0bea8e03 to your computer and use it in GitHub Desktop.
knockout "data-" attribute binding handler
// Usage:
// <span data-bind="text: FromDate, data: { 'item' : ItemID}"></span> => 'data-item' has ItemID() value
// <span data-bind="text: FromDate, data: { 'value' : $data}"></span> => 'data-value' will be rendered as JSON
// <span data-bind="text: FromDate, data: { 'item' : ItemID, value' : $data}"></span> => more than one data attribute
//
// or something confusing as
// <span data-bind="text: FromDate, data: ItemID, name: 'item'"></span>
ko.bindingHandlers.data = {
name: ko.observable(''),
update: function (element, valueAccessor, allBindingsAccessor) {
var va = ko.utils.unwrapObservable(valueAccessor());
var value = "", name = "";
var d = {};
if (typeof (va) === "object") {
for (var k in va) {
var _val = ko.utils.unwrapObservable(va[k]);
if (typeof (_val) !== "object") {
d["data-" + k] = _val;
} else {
d["data-" + k] = ko.toJSON(_val);
}
}
} else {
value = va;
name = ko.utils.unwrapObservable(allBindingsAccessor().name !== undefined
? allBindingsAccessor().name
: ko.bindingHandlers.data.name);
d["data-" + name] = value;
}
ko.bindingHandlers.attr.update(element, function () {
return d;
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment