home ~ projects ~ socials

bind One JavaScript Function Back To An Object

This might be the way to do it. ---

It's working, but would like someone to vet it.

It's not really binding, but it's doing what I want

TODO: Basically the same thing as: id: 2ai9647o - need to combine those two

JavaScript

class Widget {
    constructor() {}
    init() {
        testInput.addEventListener("input", () => { 
            this.level1.call(this, testInput.value)
        })
    }
    level1(value1) {
        console.log(`One: ${value1}`)
        this.level2(value1)
    }
    level2(value2) {
        console.log(`Two: ${value2}`)
    }
}

document.addEventListener("DOMContentLoaded", () => {
    const w = new Widget()
    w.init()
})

see this also: 2ai9647o

This is an example of how to use bind to send a function to another function while allowing it to have access to a .this

see also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Bind and Timer Example</title>
</head>
<body>
    
<script>

const timeFunctionExecution = (func, args) => {
    const t0 = performance.now()
    const payload = func.call(null, [args])
    const t1 = performance.now()
    const time = t1 - t0
    const report = {
        "payload": payload,
        "time": time
    }
    return report
}

function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}

const functionToTime = (args) => {
    console.log('functionToTime ACTIVATED!!!')
    sleep(1439)
    return "The Cat Has Landed"
}

const topLevelItem = {
    x: 42,
    getX: function() {
        return this.x 
    }
}

const test1 = timeFunctionExecution(functionToTime, {})
console.log(test1)

const unboundDemo = topLevelItem.getX 
const test2 = timeFunctionExecution(unboundDemo.bind(topLevelItem), {})
console.log(test2)

</script>

</body>
</html>
-- end of line --