代码之家  ›  专栏  ›  技术社区  ›  yessoos

在触发的处理程序中使用类属性

  •  0
  • yessoos  · 技术社区  · 2 年前

    我构建了一个简单的JS类,它在对象上设置一个监听器,并在更改事件上触发一个方法。 该方法搜索预加载的配置以找到相应的值,然后对其进行处理。 我似乎无法从触发的方法内部访问父对象的属性,除非它作为额外的参数传递。

    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>
    

    这是通常的行为,还是有更直接的方法?

    1 回复  |  直到 2 年前
        1
  •  -1
  •   Marking    2 年前

    问题是数据没有正确地传递给回调函数。在构造函数中,将数据作为对象文字传递给回调函数。但是,当调用回调函数时,数据将作为字符串传递。这是因为对象文字在传递给回调函数时被转换为字符串。要解决此问题,需要将数据作为引用传递给回调函数。一种方法是使用箭头函数语法。以下是修复的代码:

    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" }
    };
    };
    }