Another way to achieve this is to use the attachEventOnce
method from EventProvider.
oModel.attachEventOnce("requestCompleted", function(oEvent) {
console.log(JSON.parse(oEvent.getParameter("response").responseText));
}, this);
It's best to use this approach when you only need to react to one request, and not all. Otherwise, if you use oModel.attachRequestCompleted(...)
, all requests will go through the same handler function.
You can also use method chaining to make this a little easier.
oModel.attachEventOnce(...)
returns the object that called the method, so you can load your data and handle the callback all in one statement.
oModel.attachEventOnce("requestCompleted", function(oEvent) {
console.log(JSON.parse(oEvent.getParameter("response").responseText));
}, this).loadData("http://127.0.0.1/data/config.json");
This will first execute the loadData()
request, and then console the response when the request has been completed. It will only use the callback function the first time a request is made. Subsequent requests will not go through the callback function.
If you want ALL requests to go through the SAME callback function, you can do the same thing but using oModel.attachRequestCompleted(...)
oModel.attachRequestCompleted(function(oEvent) {
console.log(JSON.parse(oEvent.getParameter("response").responseText));
}, this).loadData("http://127.0.0.1/data/config.json");
This will execute the loadData()
request, console the response, and also console the response of all subsequent requests.
NOTE: Be careful using this
in the callback functions. If you don't pass this
as a parameter of the attachRequestCompleted(...)
or attachEventOnce(...)
methods, then this
will lose it's original context as the controller, and inherit the context of the object calling the function. herrlock's answer demonstrates how the context of this
changes.
Event Provider API Reference