Knockout.js not updating view from dynamic ajax call
-
26-10-2019 - |
سؤال
I am trying to get knockout.js to update my view after an ajax call but having no luck. I keep getting the error below. It errors at app.interactive.updateBindings
. The parseBindingAttribute viewModel parameter is undefined.
Error:
Unable to parse binding attribute. Message:
ReferenceError:interactive
is not defined;
Attribute value:template: { name: 'answerTmpl', foreach: interactive.answers }
Dynamic HTML:
<div id="questions">
<div id="answers" data-bind="template: { name: 'answerTmpl', foreach: interactive.answers }">
</div>
</div>
<script type="text/javascript">
app.viewModel.interactive.answers(@Html.Raw(@Model.Answers.ToJson()));
app.interactive.updateBindings(document.getElementById('answers'));
</script>
<script id="answerTmpl" type="text/html">
<div>
<span></span> <input type="checkbox" name="Answer" />
</div>
</script>
My .js file:
(function (app, $, undefined) {
app.viewModel = {};
app.interactive = {};
app.interactive.callback = function () { };
app.viewModel.interactive = {
content: ko.observable('test'),
answers: ko.observableArray()
};
app.interactive.init = function () {
ko.applyBindings(app.viewModel);
};
app.interactive.updateBindings = function (element) {
ko.applyBindingsToNode(element);
};
app.interactive.init();
})(window.app = window.app || {}, jQuery);
I can fixit with the below code:
ko.applyBindingsToNode(element, null, app.viewModel);
But now I am getting this error:
invalid 'in' operand jQuery.template
if (templateId in jQuery['template'])
المحلول
I feel like an idiot. I didn't even reference the jquery template script.
نصائح أخرى
It looks a little confusing. You have app.viewModel.interactive and then app.interactive. I could well be missing something but would you try to applyBindings to more simply namespaced viewmodel and work up from there?