Knockout binding handler pass array of objects

784 Views Asked by At

Is it possible to pass array value with square brackets for binding handler?, ie:

<div data-bind="validator: [{class: RequiredValidator}, {class: EmailValidator}]"></div>

It works fine for one object:

<div data-bind="validator: {class: RequiredValidator}"></div>

Class value is not observable, just javascript object.

It throws Message: Unexpected token ) error.

Or I need some other syntax? I could wrap it with object, but prefer not.

I took snapshot of project with this issue, available here: http://balin.maslosoft.com/array-validators/dev/validator.php

Open console, and object validators will show configuration, while array will fail.

Here is fiddle with minimal example: http://jsfiddle.net/piotr/fu8d0hm3/

3

There are 3 best solutions below

0
PeterM On BEST ANSWER

It turned out that it was problem with knockout-es5 modification for two-way bindings.

Original plugin is not affected. I've created pull request to address this issue.

The problem was binding preprocessing, which produced invalid code if array value was passed.

3
super cool On

All you need to set a VALID value to the key you are passing . As in you case RequiredValidator is not defined so keep that in quotes to resolve the issue .

view:

<div data-bind="validator: [{class: 'RequiredValidator'}, {class: 'EmailValidator'}]"></div>

viewModel:

ko.bindingHandlers.validator = {
  init: function(element, valueAccessor) {
    console.log(valueAccessor()); //check console window for o/p
  }
}
ko.applyBindings();

check sample here

10
Roy J On

It works for these. Might the problem be in your binding handler?

ko.bindingHandlers.validator = {
  init: function(el, va) {
    var value = va();
    console.debug(value);
  }
};

vm = {
  something: ko.observable('hi')
};

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="validator: ['one']"></div>
<div data-bind="validator: [something()]"></div>
<div data-bind="validator: [{class: something()}, {class:'whatever'}]"></div>