Search code examples
javascriptsapui5

Passing "this" context to javascript function on SAPUI5


I have following funcion of ODataModel object:

serviceModel.read("/Users(1)", {
  success: function(userModel) {
    this.getView().setModel(userModel, "userAuthenticated");
  }
});

I get error when invoke to this.getView() function. this is nor recognized and have null value. I've opted for using this not very elegant solution:

var viewCurrent = this.getView();
serviceModel.read("/Users(1)", {
  success: function(userModel) {
    viewCurrent.setModel(userModel, "userAuthenticated");
  }
});

Anyway, I would like how is the correct way for passing "this" context as parameter.


Solution

  • If you read the documentation you'll see that context doesn't correlate with the functions context.

    To set the context correctly, you have a couple of options. The first is using an arrow function which binds this to the current scopes this value.

    serviceModel.read(
      "/Users(1)", {
        success: (userModel) => {
          this.getView().setModel(userModel, "userAuthenticated");
        },
    
    ...
    

    If you're running in an environment which doesn't support arrow functions, you can always use bind which allows you to specify the value of this inside of a function.

    serviceModel.read(
      "/Users(1)", {
        success: function(userModel) {
          this.getView().setModel(userModel, "userAuthenticated");
        }.bind(this),
    
    ...