Rivets.js-上[事件]活页夹和回调函数

时间:2019-04-07 07:58:37

标签: javascript rivets.js

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

我将一个对象与数据和函数(控制器)绑定在一起。该对象在JS类中管理。使用on [event]活页夹,将调用一个函数,但它无法访问对象本身(在我的示例中,重要数据变量)。可以这样做吗?

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

1 个答案:

答案 0 :(得分:0)

解决方案是在我的类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);
        }
      }
    };
  }
}