javascript - ES6:如何使用 getter 和方法更新类中的属性
问题描述
我想要一种方法来更新通过 getter 定义的属性值。该属性获取 HTML 数据属性的值,而 mut 方法只是将其增加 1 并在 HTML 中更新它。单击按钮时调用该方法。比下次再次单击按钮时,我想 getter 重新定义属性的值,获取数据属性的新值。但它不会发生。
该环境允许我使用 jQuery,因为作为构造函数的主要参数的“元素”是代表组件的 HTML 目标元素的 jQuery 对象。
这是代码:
import {Components} from 'MyCustomLibrary';
export default class Calendar extends Components{
get CurrentMonth(){
return this.element.data('calendar-currentmonth');
}
onClickHandler(){
this.getNewCalendar(this.CurrentMonth);
}
getNewCalendar(month){
/****
/* jQuery substituted with Vanilla for suggestion in the comments
$('[data-calendar-currentmonth]').data('calendar-currentmonth',month+1);
****/
let dataAttributes = document.querySelectorAll('[data-calendar-currentmonth]');//.data('calendar-currentmonth',month+1);
dataAttributes.forEach(function(e){
e.setAttribute('data-calendar-currentmonth',parseInt(month)+1);
});
}
constructor(element){
super(element) //element is the html target of component, and it's a jQuery object
this.element.on('click', this.onClickHandler.bind(this));
}
}
在 html 中,我的按钮是一个带有 'data-calendar-currentmonth=2' 属性的锚标记。最初它设置为 2,比我第一次单击时,函数更新属性,我可以通过控制台在我的 html DOM 中看到“3”。
但是当我再次单击时,CurrentMonth 的值再次为“2”,并且更多,html 不再更新(可能只是因为属性值没有更新并且 2+1 始终为 3)。
不是每次调用它定义的属性时都应该执行getter吗?那么为什么它在第二次调用的时候没有获取到 HTML 里面的新值呢?
解决方案
实际上我发现是 jQuery 弄得一团糟。我只是重新定义了 Vanilla 中的所有变量,它工作得很好。
我已经删除了该get CurrentMonth
语句,我只是直接在调用getNewCalendar
.
比我的代码变成这样:
onClickHandler() {
this.getNewCalendar(this.element[0].getAttribute('data-calendar-currentmonth'));
/*** 'this.element' is actually a jQuery object. Calling element[0] it comes back to plain js ***/
}
getNewCalendar(month) {
/****
/* jQuery substituted with Vanilla for suggestion in the comments
$('[data-calendar-currentmonth]').data('calendar-currentmonth',month+1);
****/
let dataAttributes = document.querySelectorAll('[data-calendar-currentmonth]');//.data('calendar-currentmonth',month+1);
dataAttributes.forEach(function(e) {
e.setAttribute('data-calendar-currentmonth', parseInt(month) + 1);
});
}
constructor(element) {
super(element) // element is the html target of component, and it's a jQuery object
this.element.on('click', this.onClickHandler.bind(this));
}
推荐阅读
- php - 在目录中按名称搜索特定文件
- angular - 'MonoTypeOperatorFunction 类型的参数
' 不可分配给 'UnaryFunction 类型的参数 , 可观察的 >' - php - PHP Imap 连接问题
- html - 仅从主页隐藏横幅
- firebase - Firebase 模拟读取被拒绝
- ajax - Drupal 如何在没有 hook_form_alter 的情况下重建 à 表单
- sql - 在 STRING_AGG 中产生 DISTINCT 值
- java - 如何打开新标签
- angular-ui-bootstrap - 选择与来自 Rest 客户端的动态数据一起使用时不显示的选项。为 UI 使用 Angular 6 和 Bootstrap
- sql - Redshift:与其他用户打开 2 种聊天类型的用户计数