Skip to Content

Hello everybody,

i would like to share a simple way to have the controller reference this available in the callback functions of model crud functions (create, update, remove …). For javascript experts, the given solution will be logic – for abap’ers starting with javascript, i hope this will be quite helpful.

What do we want?

I wanted to get rid of var that = this; before excuting model operations. In our callback handlers i wanted to use this (controller). We intensivly read about this/that and javascript context and found a better pattern to implement callback handlers. As mentioned for javascript expersts this will be logic.

For quite some time we implemented the success & error callback functions with this pattern:

var that = this;

oModel.create(…., function:{

//Success

that.callMethodSuccess();

}, function : {

//Error

that.callMethodError();

}

The pattern for avoiding that in the callback functions proceed as following:

Define a variable as a function, with the parameters described in the api reference:

var funcOnSucces = function(oData, response) {

//calback code with this

this.callMethodSuccess(); //<- this is the controller reference if the model operation is called with .bind(this)

}

var funcOnError = function(oError) {

this.callMethodError();

}

In the model call use bind() method from javascript:

oModel.create(…, funcOnSuccess.bind(this), funcOnError.bind(this));

I hope this post will help people starting with sapui5 to get the proper controller context into the model callback functions.

As usual feedback & comments are well appreciated.

I wish you all a nice day.

Kind regards,

Michael

To report this post you need to login first.

3 Comments

You must be Logged on to comment or reply to a post.

  1. Daniel Ruiz

    I would particularly choose var that = this most cases over .bind(this) mainly because the clousure version works a lot faster than bind.. and I always choose speed, most of all when dealing with a “browser” which is client-side and I usually don’t have as much control (or none) as a server.. so fast code prevail always.

    Other than that, arrow is a lot faster than .bind(this).. I understand the benefit of “readability” using the .bind(this) but again, readability of code should not impact performance and when it does, the developer usually would pay to read whatever code performs better because the user should never pay the price.

    @Maksim: time to let the jQuery dependency go.. we had an even stronger player in the past called Flash with 99.9% market penetration and died.. jQuery has the days counted, in fact it really only slow down UI5 doing things like .html() to manipulate content of DOM nodes.

    (0) 

Leave a Reply