knockout.js - knockout foreach in the middle of a table -
i have table so:
<table> <thead> <tr> <td>column 1</td><td>column 2</td> </tr> </thead> <tr> <td>static 1a</td><td>static 2a</td> </tr> <tr> <td>dynamic 1b</td><td>dynamic 2b</td> </tr> <tr> <td>dynamic 1c</td><td>dynamic 2c</td> </tr> </table>
the dynamic fields need knockout foreach iterate properties of object. thing can think like:
<tbody data-bind="foreachprop: properties"> <tr><td><span data-bind="text: propertyname"></span></td><td><span data-bind="text: value"></span></td></tr> </tbody>
which technically works, screws styling because static row should part of tbody. else can bind each? must missing simple solution.
update: i'm not using "foreach", i'm using custom function iterates through properties. when try use <!-- ko foreachprop:> properties -- following console error:
uncaught error: binding 'foreachprop' cannot used virtual elements
here foreachprop function
ko.bindinghandlers.foreachprop = { transformobject: function (obj) { var properties = []; (var key in obj) { if (obj.hasownproperty(key)) { var newobj = obj[key]; newobj.propertyname = key; properties.push(newobj); } } return properties; }, init: function (element, valueaccessor, allbindingsaccessor, viewmodel, bindingcontext) { var value = ko.utils.unwrapobservable(valueaccessor()), properties = ko.bindinghandlers.foreachprop.transformobject(value); ko.applybindingstonode(element, { foreach: properties }); return { controlsdescendantbindings: true }; } };
you can use foreach
without container element (documentation: note 4) handle this, can use containerless control flow syntax. need specfial comment line can put foreach
:
<tbody data-bind=""> <tr> <td>static 1a</td><td>static 2a</td> </tr> <!-- ko foreach: properties --> <tr> <td> <span data-bind="text: propertyname"></span> </td> <td> <span data-bind="text: value"></span> </td> </tr> <!-- /ko --> </tbody>
if using custom binding foreachprop
need configure work virtual elements. can after bindinghandlers declaration with:
ko.virtualelements.allowedbindings.foreachprop = true;
you should note may need rewrite dom manipulation logic inside custom binding support virtual elements. can find extensive documentation on virtualelements
helpers in documentation: creating custom bindings support virtual elements
Comments
Post a Comment