12

In some part of onInit function of a controller in a SAPUI5 application there is an auto generated code like this:

    this.getView().addEventDelegate({
            onBeforeFirstShow: function() {
                // Some codes
            }.bind(this)
        });

Now my question is what does .bind(this) mean? What does it do? Is it a pure JavaScript code or it is related to SAPUI5?

MJBZA
  • 4,796
  • 8
  • 48
  • 97
  • 3
    @Mahdi, next time, please search around a bit before asking. – Cerbrus Feb 20 '17 at 12:23
  • 1
    **For UI5 developers:** it's important to note that `bind` returns a new function. This makes detaching the handler (e.g. in `onExit` | `exit`) more difficult. Your IDE should **not** suggest to use `bind`. Instead, pass the listener object as an argument if possible. See https://stackoverflow.com/a/61603539/5846045 or https://stackoverflow.com/a/61686925/5846045 – Boghyon Hoffmann Jun 09 '20 at 10:10

3 Answers3

11

Yes, it's pure JavaScript code, you can learn more about what bind is and does here

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

In this case what it does is basically binding the current this to that function, so when onBeforeFirstShow is called, the this inside that function will be the one passed to the bind function.

You may also want to look at the new arrow function syntax in ES6, it auto binds the current this so bind(this) is not necessary.

Mike
  • 14,010
  • 29
  • 101
  • 161
Tiago Engel
  • 3,533
  • 1
  • 17
  • 22
  • So basically it is an extra step to tell the JS code where should the function context being set, correct? Then what would happen if there is no code to bind the current 'this' context? – Harvey Lin Feb 28 '19 at 20:08
10

It binds the listener of the function to the current class, then when you use this pointer inside of the onBeforeFirstShow function, the this pointer refer to encapsulated class and you can access to its members.

  • This is because of bind(this). This allows to add new parameters. Please check the explanation here: https://stackoverflow.com/a/10115970/1735425 – Ricardo Magalhães Sep 21 '21 at 12:51
1

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Syntax

fun.bind(thisArg[, arg1[, arg2[, ...]]])

Reference to Mozilla Developer Network

cnbandicoot
  • 372
  • 3
  • 13