Search code examples
jquerymvvmknockout.jsviewmodelknockout-mapping-plugin

knockout error, viewmodel not bound


my code is this:

<div id="DivToUpdate">
    <div>
        SELECTED ROOM:
        <input type="text" id="currentRoom" /></div>
    <div id="messagesList">
        <table>
            <tbody data-bind="foreach: model.Messages">
                <tr data-bind="text: Message">
                </tr>
            </tbody>
        </table>
    </div>
</div>

<script type="text/javascript">
var viewModel = {};
$('#DivToUpdate').click(function () {
    $.getJSON("/ControllerAction/JsonPopulateMessages", { jsonRoom: $('#currentRoom').val() }, function (data) {
        var trueData = JSON.stringify(data);
        alert(trueData);
        viewModel.model = ko.mapping.fromJSON(trueData);
        ko.applyBindings(viewModel);
    });
});
  </script>

my returned JSON data is in the format like this:

 {"Messages":[{"Message":["yow!"]},{"Message":["hey!"]}]}

when i try to run the code and click DivToUpdate, i see nothing... table and the rows are empty.. meaning the viewmodel is not binded correctly.. and when i looked at the console of chrome, it says:

 NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7

i am starting to learn knockout and i would really appreciate if you could tell me how to fix this...


Solution

  • Your JSON looks a bit odd, remove the [] around the value of Message. I guess it should be a string right? How are you generating your JSON?

    update:

    When I look at it again, I realize that you try to bind the text to the tr-element, but a tr can only contain td-elements, so you need to add a td within your tr and bind the data to the td-element instead.

    Try this instead:

        <div id="messagesList">
            <table>
                <tbody data-bind="foreach: model.Messages">
                    <tr>
                       <td data-bind="text: Message"></td>
                    </tr>
                </tbody>
            </table>
        </div>