Search code examples
javascriptjqueryknockout.jsknockout-mapping-pluginx-editable

knockout js template passing json data source to template


I am new to Knockout and its templating feature, I have the following html, can somebody help me framing a suitable template to replace its string literals and data source, I am using x-editable,#

<tr data-bind="foreach: fundClasses">
    <td class="span1">
        <span data-bind="visible: $index() == 0">  Rate Index</span>
    </td>
    <td class="span1 protected">
        <span data-bind=" editable:INDEX_ID,  editableOptions: {name:'INDEX_ID',mode: 'popup',type: 'select', source: rateIndex,pk: ID, url: '/create/EditInPlace'}"></span>
    </td>
</tr>

I would like to replace rateIndex, INDEX_ID in the snippets above, any help on this is greatly appreciated.

Thanks George


Solution

  • I figured it out myself, so thought of answering so that would help others looking for similar issues,

    Template:

    <script id="textBoxTemplate" type=“text/html”>
       <!-- ko foreach: $data -->
        <td class="span1">
            <span data-bind="visible: $index() == 0,text:title">  </span>
        </td>
        <td class="span1 protected">
             <span data-bind="editable:$data[field],editableOptions: {  mode: 'popup', pk: ID, url: '/create/EditInPlace'}"></span>
       </td>
       <!-- /ko -->
    

    Usage:

    <tr data-bind="templateWithContext: { name: 'textBoxTemplate', data: fundClasses, context: { title: 'Index', field:'INDEX_ID' }}"></tr>
    

    Binding Handler:

    ko.bindingHandlers.templateWithContext = {
        init: ko.bindingHandlers.template.init,
        update: function (element, valueAccessor, allBindings, data, context) {
            var options = ko.utils.unwrapObservable(valueAccessor());
    
            ko.utils.extend(context, options.context);
    
            return ko.bindingHandlers.template.update.apply(this, arguments);
        }
    };