0

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.

Boghyon Hoffmann
  • 15,517
  • 8
  • 61
  • 146
Cesar Miguel
  • 503
  • 1
  • 10
  • 33

1 Answers1

1

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),

...
Mike Cluck
  • 30,526
  • 12
  • 76
  • 90