简体   繁体   中英

Rivets.js - on-[event] binder and callback function

Demo app : https://glitch.com/~rivets-so

I bind an object with data and functions (controller). This object is managed in a JS class. With on-[event] binder, a function is called, but it can't access to to object itself (in my sample, the importantData variable). Is it possible to do that ?

index.html :

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Hello!</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/rivets/0.9.6/rivets.bundled.min.js"></script>
    <script type="module" src="/main.js" defer></script>
  </head>  
  <body>
    <h1>
      Simple app
    </h1>
    <div id="content">
      <span rv-on-click="data.controller.click">{ data.data.Nom }</span>
    </div>
  </body>
</html>

main.js :

import { Controller } from '/controller.js';

var controller = new Controller('Important data');

rivets.bind(document.querySelector('#content'), { data: controller.getData() });

controller.js :

export class Controller {
  constructor(importantData) {
    this.importantData = importantData;
  }

  getData() {
    return {
      data: {
        Nom: 'Francis'
      },
      controller: {
        click: function(event, model) {
          console.log("Click !");
          // this represent the element clicked, not the class itself
          console.log(this.importantData);
        }
      }
    };
  }
}

The solution is to use an arrow function in my class Controller :

export class Controller {
  constructor(importantData) {
    this.importantData = importantData;
  }

  getData() {
    return {
      data: {
        Nom: 'Francis'
      },
      controller: {
        click: (event, model) => {
          console.log("Click !");
          // this represent the element clicked, not the class itself
          console.log(this.importantData);
        }
      }
    };
  }
}

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