Sunday, March 22, 2015

knockout.js "data-" attribute binding handler

Gist: https://gist.github.com/dirnthelord/ca0fcbb25c7f0bea8e03

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;
});
}
};
Usage:  
=> single , observable attribute
<span data-bind="text: FromDate, data: { 'item' : ItemID}"></span>
'data-item' has ItemID() value  
=> single, object as the value
<span data-bind="text: FromDate, data: { 'value' : $data}"></span> 'data-value' will be rendered as JSON  
=> multiple, mixed data types
<span data-bind="text: FromDate, data: { 'item' : ItemID, value' : $data}"></span> objects will be converted to JSON and primitive data types to corresponding value
You can also enter non observables and it will be rendered as you want.
or something confusing as <span data-bind="text: FromDate, data: ItemID, name: 'item'"></span>