简体   繁体   中英

how to move class.bind condition from view to model in Aurelia repeat.for

While implementing a class.bind I stumbled across one issue(at least I see it as an issue), I do not really like to have too much logic in the view and was thinking to move to the model of the component but it appeared to be tricky. I am implementing the step progress bar

<template >
  <ul class="all-steps">
    <li repeat.for="step of steps" class.bind="current === step ? 'active': (previous.indexOf(step) >= 0 ? 'done':'')">${$index + 1}</li>
  </ul>
</template>

Is there any way I can move all this class assigning logic to a view? I tried to create a binding function with dirty binding but apparently passing the step from the view causes Unhanded rejection exception any suggestions are appreciated

All you need to do is write a function that takes the various parameters. The best part is that this won't trigger dirty checking. Aurelia will only call the function if the value of the parameters change.

Here's an example: https://gist.run?id=837b35139b924682143e74f4e7ca85ba

app.html

<template>
  <ul class="all-steps">
    <li repeat.for="step of steps" class="${calculateClass(current, step)}">Step 1: ${$index + 1} (${calculateClass(current, step)})</li>
  </ul>
</template>

app.js

export class App {
  current = 3;
  steps = [ 1, 2, 3, 4, 5 ];
  previous = [ 1, 2 ];

  calculateClass(current, step) {
    console.log(`called. current = ${current}, step = ${step}`)
    if(current === step) {
      return 'active';
    } else if (this.previous.indexOf(step) >= 0 ) {
      return 'done';
    } else {
      return '';
    }
  }
}

index.html

<!doctype html>
<html>
  <head>
    <title>Aurelia</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <style>
      li {
        background-color: green;
      }

      li.active {
        background-color: yellow;
      }

      li.done {
        background-color: red;
      }
    </style>
  </head>
  <body aurelia-app>
    <h1>Loading...</h1>

    <script src="https://jdanyow.github.io/rjs-bundle/node_modules/requirejs/require.js"></script>
    <script src="https://jdanyow.github.io/rjs-bundle/config.js"></script>
    <script src="https://jdanyow.github.io/rjs-bundle/bundles/aurelia.js"></script>
    <script src="https://jdanyow.github.io/rjs-bundle/bundles/babel.js"></script>
    <script>
      require(['aurelia-bootstrapper']);
    </script>
  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM