Rivets.js - on-[event] 活页夹和回调函数

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

演示应用程序:https://glitch.com/~rivets-so

我用数据和函数(控制器)绑定了一个对象。该对象在 JS class 中进行管理。使用 on-[event] 活页夹,一个函数被调用,但它无法访问对象本身(在我的示例中,importantData 变量)。可以吗?

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);
        }
      }
    };
  }
}

解决方案是在我的 class 控制器中使用箭头函数:

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);
        }
      }
    };
  }
}