renathy
renathy

Reputation: 5345

Conditional binding: apply binding only if some criteria met

Is there a way to apply one binding in knockout if some criteria are met and do not apply this binding if those critera are not met?

<div data-bind="custombinding: $data.values"></div>

I need to apply this binding if $data.canEdit is true, otherwise I do not need to apply this binding.

The exact example is more complicated.

Upvotes: 3

Views: 5519

Answers (2)

Jeroen
Jeroen

Reputation: 63699

I don't think you should typically make different bindings dependent on eachother. Instead, create a dependency on logical view model properties (which allows you to easily unit test involved logic too). You already mention you have such a property: canEdit, a boolean observable I'd assume.

If you do, you could create custom bindings that go like this:

<div data-bind="custombinding: { onlyIf: canEdit, vals: values }"></div>

In addition I also second @JeremyBarnes' suggestion (using an if binding), e.g.:

<!-- ko if: canEdit -->
<div data-bind="custombinding: values"></div>
<!-- /ko -->

Furthermore, if you must, you can include something like this in your view:

<div data-bind="custombinding: !!canEdit() ? values : []"></div>

As a side note I'd suggest encapsulating that ternary operator's logic in a computed observable.


However, going directly to the question asked, if you check the custom binding documentation you can find that you could probably do what you want, because binding handlers have access to:

  • allBindings for that particular element; as well as
  • bindingContext.$data to access the view model (and e.g. find canEdit through that)

It's impossible to give more precise answers or guidance, as your question is rather low on details.

Upvotes: 6

Jeremy Barnes
Jeremy Barnes

Reputation: 677

Try the knockout if-binding.

That binding leaves out the HTML if the condition is not met (the div would be excluded).

Otherwise, you'll want to bind it to an object in the JS that is conditionally set up.

Upvotes: 1

Related Questions