1
votes

So I am working with a JSON object of CSS attributes/divs, something like:

"#myDiv": {
    "position": "absolute",
    "max-height": "225px"
  },

And I am binding this object to a div using KnockoutJS's style binding:

<!-- ko with: $root.Styles['#myDiv'] -->
     <div data-bind="style:{
         position: position,
         maxHeight: $data['max-height']
       }"></div>
<!-- /ko -->

Position binds fine, and any other properties that do not have to be accessed explicitly are OK as well. Is it possible to bind something like $data['max-height'] within a KnockoutJS style binding?

*I'd also like to note that I can succesfully bind $data['max-height'] to a text field, but it always fails with a syntax error when binding a style.

Thoughts? :)

Update

For anyone still experiencing this, I am using VS 2015 with includes Browser Link by default. Disabling this feature removes all syntax errors. Add this to your web.config:

<appSettings>
<add key="vs:EnableBrowserLink" value="false" />
</appSettings>

Thanks again to @Jeroen for pointing out the error wasn't caused by KO.

1
Try style: { maxHeight: function($data) { return $data['max-height'] } } - Jonathan
No luck, still gives me a 'unrecognized expression' error. There's has to be some quirky syntax to allow this :p. - System Out Of Memory

1 Answers

0
votes

The code you've posted should work fine with styles like this:

ko.applyBindings({
  Styles: {
    "#myDiv": {
      "position": "absolute",
      "max-height": "225px"
    }
  }
});
div {
  background-color: pink;  /* to demo "max-height" is working... */
  font-size: 80px; /* to demo "max-height" is working... */
  top: 50px; /* to demo "position" is working... */
  left: 50px; /* to demo "position" is working... */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

<!-- ko with: $root.Styles['#myDiv'] -->
<div data-bind="style:{
         position: position,
         maxHeight: $data['max-height']
       }">X
  <br>X
  <br>X
  <br>X
  <br>
</div>
<!-- /ko -->

The position is working as you can tell from the fact that top and left from the css are picked up.

The max-height is picked up as you can see from the pink background not going beyond 225px in height.