Search code examples
cssjsrenderjsviews

Logic in JsViews css-tag


I am trying to put logic in a css-width in a data-link in jsViews. The two following approaches did not work:

{{for Items}}
    ...
    <td id="show-keys" data-link="css-width{~root.ShowKeys ? '200px' : '400px'}">

or

{{for Items}}
    ...
    <td id="show-keys" data-link="css-width{:~keysWidth()}">
...

<script type="text/javascript">
    ...
    var app = {
        ...
        helpers: {
            showKeys: function () {
                //debugging shows that this never gets fired
                return app.ShowKeys ? '400px' : '100px';
            }

How do I appropiatly base a css-value on a property so that it changes dynamically?


Solution

  • Here is a jsfiddle that shows a few variants: http://jsfiddle.net/BorisMoore/GZPvZ/

    Your first expression missing a :

    data-link="css-width{~root.ShowKeys ? '200px' : '400px'}"
    

    should be

    data-link="css-width{:~root.ShowKeys ? '200px' : '400px'}"
    

    For the second approach, using a helper, apart from the naming of the helper (I think you meant it to be keysWidth - as @BKimmel points out) - you need to declare the fact that it is a computed observable with a dependency on ~root.showKeys - which you do like this:

    function keysWidth() {
        return app.showKeys ? '400px' : '100px';
    }
    
    keysWidth.depends = "~root.showKeys"; // or you can write ... = [app, "showKeys"]
    

    Alternatively you can not declare the dependency, but pass it in as an argument:

    data-link="css-width{:~keysWidth3(~root.showKeys)}"
    

    Helpers can be declared globally, or passed in with the link call.

    See the jsfiddle for details...

    Update: There are now some new samples that cover CSS and class binding. There is a tutorial sequence on data-linking, which includes this page on data-linking class, this on on toggling class, and this one on linking to CSS attributes.