[英]Rivets.js - on-[event] binder and callback function
演示應用程序: https : //glitch.com/~rivets-so
我用數據和函數綁定一個對象(控制器)。 該對象在JS類中管理。 使用on- [event] binder,會調用一個函數,但它無法訪問對象本身(在我的示例中,為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);
}
}
};
}
}
解決方案是在我的類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);
}
}
};
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.