0

I have a table being created that looks like the following:

<table>
  <thead>
    <tr>
        <th>Index</th>
        <th>Last Name</th>
        <th>First Name</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: $data">
    <tr data-bind="css: rowClass">
        <td data-bind="text: $index"></td>
        <td data-bind="text: LName"></td>
        <td data-bind="text: FName"></td>
    </tr>    
  </tbody>
</table>

I am using the knowckout.mapping functionality to take my data from my controller in and encoding to json. My javascript is below.

<script type="text/javascript">
    $(function () {
        var viewModelJSON = ko.mapping.fromJSON('@Html.Raw(jsonData)');

        viewModelJSON.rowClass = ko.computed(function () {
            return 'success';
        });

        ko.applyBindings(viewModelJSON);
    });
</script>

Everything was working great until I added the data-bind for css rowClass. I'm simply trying to return the success class and but the javascript console reports "Unable to parse bindings" and "rowClass is not defined". I've also tried declaring the rowClass function like:

viewModelJSON.rowClass = ko.computed(function () {
            return 'success';
        }, viewModelJSON);

But still with no luck. Any thoughts on what I'm doing wrong?

Working Solution

Updating my JavaScript seems to have solved my problem:

<script type="text/javascript">
    $(function () {

        var mapping = {
            create: function (options) {
                return new myImportItem(options.data);
            }
        }

        var myImportItem = function (data) {
            ko.mapping.fromJS(data, {}, this);

            this.rowClass = ko.computed(function () {
                return 'success';
            }, this);
        }

        var viewModelJSON = ko.mapping.fromJSON('@Html.Raw(jsonData)', mapping);            

        ko.applyBindings(viewModelJSON);
    });
</script>

1 Answer 1

1

Where you are adding the css binding, the context will be an item in your array. However, you have placed the rowClass computed at your root level.

If you want to bind against it you would have to do it like css: $parent.rowClass or css: $root.rowClass (they would be the same in this case).

If you want each item in your array to have a rowClass computed, then you would want to look at using the mapping plugin's mapping options.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much. I seemed to have gotten it working. I'm updating my answer with my working code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.