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
  • 17,103
  • 12
  • 72
  • 170
Cesar Miguel
  • 661
  • 1
  • 13
  • 38

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
  • 31,869
  • 13
  • 80
  • 91