3

Binding to oninput event of an input element like so:

oninput: this.updateNote.bind(event, note)

where note is a simple object ({ completed: bool, text: string}) and event is the InputEvent.

I have defined updateNote as follows:

updateNote(note, event) {
...
}

It works with an oddity I can't explain.

The arguments for updateNote are in reverse order compared to the bind() call, yet note is the correct object and event is the InputEvent.

5
  • 3
    The first argument to .bind is the new this value, not the first argument to pass Commented Nov 16, 2019 at 0:21
  • That's true, and furthermore you may be misunderstanding what .bind() does. The values you pass to .bind() are actual values to be passed at the time the bound function is called. You cannot use .bind() to reverse the order of parameters to a function, in short. Commented Nov 16, 2019 at 0:23
  • It'd probably help if you could explain what you're actually trying to accomplish. Commented Nov 16, 2019 at 0:26
  • I want to make sure updateNote() gets all the required information, thus the bind() call. If I simply set the oninput attribute to this.updateNote I wouldn't get both the note and InputEvent values. Commented Nov 16, 2019 at 0:49
  • I know the first parameter of bind sets the new this value, but I am wondering how that translates to updateNote working without issues with the arguments reversed. Commented Nov 16, 2019 at 0:49

1 Answer 1

2

When you do

this.updateNote.bind(event, note)   // (1)

you create a function boundFunc that accepts any number of arguments and calls updateNote with this equal to whatever the event variable happens to contain, one argument note and the rest of the args passed to boundFunc. So it's basically:

event = whatever

function boundFunc(...args) {
    ...updateNote.this = whatever...
    updateNote(note, ...args)
}

Now, onInput expects a function and calls it with one argument, event. Since this function happens to be our boundFunc, it's called like this:

boundFunc(event)   // (2)

and according to the above, "updateNote" is invoked like this

updateNote(note, event)

which explains the "reversed" thing. Actually, nothing is reversed. The "event" on the line (2) has nothing to do with "event" you've used on the bind line (1). That one probably contains some rubbish and is lost as long as you don't use this in "updateNote".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.