I’ve built a simple JS class which sets a listener on a object and triggers a method on change event.
The method searches preloaded config to find a corresponding value, which is then processed.
It would seem that I’m unable to access the parent’s properties from inside the triggered method unless it’s passed as an extra argument.
class allEars{
constructor(){
$('#selectObj').on('change',{cfg: this}, function(ev){
var cfg = ev.data.cfg;
var retVal = null;
for(const prop in cfg)if(cfg.optList.optID==$(this.val()))retVal=cfg.optList[prop].txt;
});
$('#tgtObj').val(retVal).trigger("change",{p: 'param'});
}
async init(){// usually pulled from db, hence async
var optList={
777: {optID: '1', txt: "first option"},
123: {optID: '2', txt: "second option"},
969: {optID: 'n', txt: "option n"}
};
};
}
<body>
<select id="selectObj">
<option value="1">This</option>
<option value="2">That</option>
<option value="n">Other</option>
</select>
<input type="text" id="tgtObj" val=""/>
</body>
Is this the usual behaviour or is there a more straight-forward approach to this?
>Solution :
The problem is that the data is not being passed to the callback function correctly. In the constructor, you are passing the data to the callback function as an object literal. However, when the callback function is called, the data is being passed as a string. This is because the object literal is being converted to a string when it is passed to the callback function. To fix this problem, you need to pass the data to the callback function as a reference. One way to do this is to use the arrow function syntax. Here is the code with the fix:
class allEars {
constructor() {
$('#selectObj').on('change', (ev) =>
{
var cfg = this;
var retVal = null;
for (const prop in cfg.optList)
if (cfg.optList[prop].optID === $(this).val())
retVal = cfg.optList[prop].txt;
});
$('#tgtObj').val(retVal).trigger("change", { p:'param' });
}
async init() // usually pulled from db, hence async
{
this.optList = {
777: { optID:'1' ,txt:"first option" },
123: { optID:'2' ,txt:"second option" },
969: { optID:'n' ,txt:"option n" }
};
};
}