Reputation: 544
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);
}
}
};
}
}
Upvotes: 0
Views: 258
Reputation: 544
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);
}
}
};
}
}
Upvotes: 0