简体   繁体   中英

bind 'this' to a imported function vanilla js

function PersonListView() {
this._html = html;
/../
}

PersonListView.prototype = {
    addPersonHandler: function (handler) {
        addList().bind(this);
        
}

function addList() {
    let elList = this._mHtml.querySelector('#todo');
    if (elList)
        elList.addEventListener('change', function () {
            var todo = document.getElementById("todo").value;
            document.querySelectorAll("input[type='text']")[0].value = "";
            handler(todo);
        });
}

i want to ask how can i bind 'this' to addList so i dont have to pass this in the parameter of the functions, i don't know what i do wrong

I suspect you actually don't want to bind the function to anything. You can just make it become the method directly:

/* file A */
export function addList(handler) {
    let elList = this._mHtml.querySelector('#todo');
    if (elList)
        elList.addEventListener('change', function () {
            var todo = document.getElementById("todo").value;
            document.querySelectorAll("input[type='text']")[0].value = "";
            handler(todo);
        });
    }
}
/* file B */
import { addList } from '…';

…
PersonListView.prototype = {
    addPersonHandler: addList,
};

(I would however advise against scattering the methods of a single class over multiple files)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM