Unexpected token with Knockout 3 and jQuery Templates

1.7k Views Asked by At

My application has one binding that uses jQuery Templates plugin to bind Knockout templates. Since upgrading to Knockout 3.x I started seeing an error:

Uncaught SyntaxError: Unable to process binding "template: function (){return { name:'tmpl',foreach:$data.children} }"
Message: Unexpected token )

The above error doesn't allow my binding to work after upgrading to Knockout ver. 3.x (e.g. 3.4.0). With older versions (e.g. 2.1.0) it works normally.

The error may be caused by some conflict with jQuery Templates plugin. Unfortunately, I have to use it in my application.

What could be the cause and the solution?

var viewModel = function() {
  var self = this;
  self.children = ko.observableArray(
    [{}]
  );
};
ko.applyBindings(new viewModel());
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://rniemeyer.github.com/KnockMeOut/Scripts/jquery.tmpl.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>

<div data-bind="template: { name: 'tmpl', foreach: $data.children }">
</div>

<script id="tmpl" type="text/html">
  <div data-bind="template: { name: 'tmpl', foreach: $data.children, templateOptions: { parentList: $data.children } }">
  </div>
</script>

1

There are 1 best solutions below

1
On

Get rid of the empty object inside your empty array. Doesn't make sense to have it there anyways.

var viewModel = function() {
  var self = this;
  self.children = ko.observableArray([]);
};
ko.applyBindings(new viewModel());
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://rniemeyer.github.com/KnockMeOut/Scripts/jquery.tmpl.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>

<div data-bind="template: { name: 'tmpl', foreach: $data.children }">
</div>

<script id="tmpl" type="text/html">
  <div data-bind="template: { name: 'tmpl', foreach: $data.children, templateOptions: { parentList: $data.children } }">
  </div>
</script>