Reputation: 139
I have this class that I export:
import $ from 'jquery';
export default class Slider {
constructor(el) {
this.el = el;
this.$el = $(el);
this.$sliderInput = this.$el.find('.slider__input');
this.$value = this.$el.find('.slider__value');
this.$changeInputs = $('[data-type=changeable]');
init() {
this.filterSystem();
this.setValue();
this.$sliderInput.on('input change', () => {
this.setValue();
// this.filterSystem();
this.$changeInputs.find('.slider__input').val(
this.$sliderInput.val()
).trigger('change');
});
this.$sliderInput.on('mouseup', () => {
this.filterSystem();
});
}
setValue() {
this.$value.text(
this.$sliderInput.val()
);
}
filterSystem() {
const self = this;// the class instance
$("em.match.js-match").css({
'background-color': '#fff',
'color': '#000'
}).filter(function () {
// no arrow function so "this" is the element instance from jQuery
const $elem = $(this);
var length = parseInt($elem.attr("data-length"));
if (self.$sliderInput.val() <= length) {
// class property
$elem.css({'background-color': $elem.attr("data-color"), 'color': '#fff'})
}
});
}
}
I can't find where my mistake is, since I wanted to adapt this code that I have into that class but it is not working as it is in the code below:
var slider = document.getElementById("rangeslider");
var output = document.getElementById("value");
output.innerHTML = slider.value;
slider.oninput = function () {
output.innerHTML = this.value;
filterSystem();
}
function filterSystem() {
$("em.match.js-match").css({
'background-color': '#fff',
'color': '#000'
}).filter(function () {
var length = parseInt($(this).attr("data-length"));
if (slider.value <= length) {
$(this).css({'background-color': $(this).attr("data-color"), 'color': '#fff'})
}
});
}
if anybody could help me find what have I missed? Obviously, this is a filter function for a slider, and I want to put this function filterSystem()
inside that class Slider.
Upvotes: 0
Views: 53
Reputation: 171679
You are needing access to two different this
in that filter()
.
Since the filter callback is a regular function (not arrow function) then the this
will be an element instance as returned by jQuery. So you need a different variable to access the class instance
Store a reference to the class this
outside the filter callback
filterSystem() {
const self = this;// the class instance
$("em.match.js-match").css({
'background-color': '#fff',
'color': '#000'
}).filter(function () {
// no arrow function so "this" is the element instance from jQuery
const $elem = $(this);
const length = parseInt($elem.attr("data-length"));
if (self.$sliderInput.val() <= length) {
// ^^^^^^^^^^^^^^^ class property
$elem.css({'background-color': $elem.attr("data-color"), 'color': '#fff'})
}
});
}
Upvotes: 1