Cesar Miguel Cesar Miguel - 1 year ago 69
Javascript Question

Passing "this" context to javascript function on sapui

I have following funcion of ODataModel object:

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

error: function(error) {

},

context: this
}
);


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");
},

error: function(error) {

},

context: this
}
);


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

Thanks.

Answer Source

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

...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download