UI5: Formatter called multiple times or too soon from an XML view

前端 未结 2 1521
逝去的感伤
逝去的感伤 2021-01-16 04:13

I\'m using OpenUI5. Using the formatter.js, I have formatted some text in my view.

But my formatter is called 3 times:

  1. When I bind the

2条回答
  •  逝去的感伤
    2021-01-16 04:28

    • Set the model to the view only when the data request is completed:

      onInit: function() {
        const dataUri = sap.ui.require.toUri("/model/data.json");
        const model = new JSONModel(dataUri);
        model.attachEventOnce("requestCompleted", function() {
          this.getView().setModel(model);
        }, this);
        // ...
      },
      

      This ensures that the formatter is called only once (invoked by checkUpdate(true) which happens on binding initialization; see below), and no further changes are detected afterwards.

    • Additionally (or alternatively), make the formatter more defensive. Something like:

      function(value1, value2) {
        let result = "";
        if (value1 && value2) {
          // format accordingly ...
        }
        return result;
      }
      

    Why does this happen?

    1. View gets instantiated.
    2. onInit of the Controller gets invoked. Here, the file model/data.json is requested (model is empty).
    3. Upon adding the view to the UI, UI5 propagates existing parent models to the view.
    4. Bindings within the view are initialized, triggering checkUpdate(/*forceUpdate*/true)src in each one of them.
    5. Due to the forceUpdate flag activated, change event is fired, which forcefully triggers the formatters even if there were no changes at all:
      [undefined, undefined][undefined, undefined]. - 1st formatter call
    6. Fetching model/data.json is now completed. Now the model needs to checkUpdate again.
    7. [undefined, undefined][value1, undefined] → change detected → 2nd formatter call
    8. [value1, undefined][value1, value2] → change detected → 3rd formatter call

提交回复
热议问题