Skip to content
Advertisement

binding viewmodel to existence of a property in knockout

I am using Knockout.js to populate a set of HTML5 <details> elements. Here is the structure:

JavaScript

The data in the ViewModel looks something like this:

JavaScript

I want to add the ability to remember the open or closed state of the details view. I have implemented this behavior previously using jQuery and localStorage1, but for this project I want to use Knockout natively instead of using jQuery.

I have added an isOpen property to the playlists in the ViewModel which is retrieved from localStorage when the page loads. However, it seems that I can’t use the attr binding in Knockout because the HTML5 spec says to look only for the presence or absence of the open attribute, not for a value.

How would I get Knockout to add and remove the open property of the <details> element as the isOpen property of the ViewModel changes?


1: Like this:

JavaScript

Advertisement

Answer

You can modify the attr binding to take into account another binding option (named attrRemoveWhenFalse here) and remove the attribute for you:

JavaScript

Demo

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement