如何有效地重置绑定控制值? [英] How to reset bound control values efficiently?

查看:22
本文介绍了如何有效地重置绑定控制值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个添加新..."带有多个 sap.m.Input 字段的屏幕.一切正常.我提交表单并且值存储在数据库中.但是一旦我重新打开这个添加新..."屏幕,我得到了包含先前输入值的表单.

I have an "Add New…" screen with multiple sap.m.Input fields. Everything is working. I submit the form and the values are stored in the DB. But once I re-open this "Add New…" screen, I get the form with previously entered values.

目前,我可以解决使用 sap.ui.core.Element 遍历所有 sap.m.Input 字段的问题,重置值:

Currently, I can solve the issue iterating over all sap.m.Input fields with sap.ui.core.Element, resetting the values:

Element.registry.forEach(el => {
    if (el.isA("sap.m.Input") && el.sId.includes(inputFieldsMask)) {
        sap.ui.getCore().byId(el.sId).setValue("");
    }
});

其中 inputFieldsMask 是相关屏幕的所有输入字段的掩码.

Where inputFieldsMask is a mask for all input fields of the relevant screen.

据我所知,Element.registry.forEach 迭代应用程序中的所有控件,因此我不确定,从性能的角度来看,它是清理田地的最佳方法.

As far as I understand, Element.registry.forEach iterates over all controls in the app, therefore I'm not sure that, from a performance point of view, it's an optimal approach to clean up the fields.

我的问题:
有没有更好的方法可以从以前输入的值中重置输入字段?

My question:
Is there a better way to reset input fields from the previously entered values?

推荐答案

根据您创建新条目所采用的方法,有多种方法可以重置控件值.通常,我们可以使用以下 API:

There are several ways to reset the control values depending on what kind of approach you took to create the new entry. Generally, we can make use of the following APIs:

  1. 上下文传递给目标容器.

这会解析目标容器中的所有相关绑定.

This resolves all the relative bindings in the target container.

<用户输入一些值并提交...>

targetContainer.unbindElement(modelName") 在编辑成功存储后.

通过解除绑定元素,相对绑定的控件值会自动重置.

By unbinding element, relatively bound control values are reset automatically.

sap.ui.getCore().attachInit(() => sap.ui.require([
  "sap/ui/core/mvc/XMLView",
  "sap/ui/model/json/JSONModel",
  "sap/base/util/uid",
], (XMLView, JSONModel, createPseudoUniqueID) => XMLView.create({
  definition: `<mvc:View xmlns:mvc="sap.ui.core.mvc" height="100%">
    <App xmlns="sap.m">
      <Page backgroundDesign="List" title="Resetting inputs via client-side Model and Context">
        <headerContent>
          <Button id="addBtn" text="Add Item" type="Emphasized" />
        </headerContent>
        <List id="myList" growing="true" items="{
          path: '/myItems',
          key: 'key',
          templateShareable: false
        }">
          <StandardListItem title="{value}" info="Key: {key}"/>
        </List>
      </Page>
      <dependents>
        <Dialog id="myDialog"
          icon="sap-icon://ui-notifications"
          title="New Item"
          draggable="true"
          class="sapUiResponsiveContentPadding"
        >
          <Input id="myInput"
            placeholder="&lt;New value>"
            valueLiveUpdate="true"
            value="{
              path: 'value',
              type: 'sap.ui.model.type.String',
              constraints: {
                minLength: 1
              }
            }"
          />
          <beginButton>
            <Button
              text="Submit"
              enabled="{= !!%{value} &amp;&amp; !%{messages>/}.length}"
            />
          </beginButton>
        </Dialog>
      </dependents>
    </App>
  </mvc:View>`,
  models: {
    undefined: new JSONModel({
      "myItems": [],
    }),
    "messages": sap.ui.getCore().getMessageManager().getMessageModel()
  },
  afterInit: function() {
    sap.ui.getCore().getMessageManager().registerObject(this, true);
    this.byId("addBtn").attachPress(handleAddPress.bind(this));
    this.byId("myInput").attachSubmit(handleSubmit.bind(this));
    this.byId("myDialog").setEscapeHandler(onESCPress.bind(this))
      .attachAfterClose(onAfterClose.bind(this))
      .getBeginButton().attachPress(handleSubmit.bind(this));
    
    function handleAddPress(event) {
      const dialog = this.byId("myDialog");
      const listBinding = this.byId("myList").getBinding("items");
      listBinding.suspend(); // Do not update the list yet
      this._currentItems = this.getModel().getProperty("/myItems"); // temp in case user cancels
      dialog.getModel().setProperty("/myItems", this._currentItems.concat({})); // new empty item
      dialog.bindElement("/myItems/" + listBinding.getLength()); // enable data synchronization via TwoWay binding
      dialog.open();
    }
    
    function onESCPress(promise) {
      const model = this.getModel();
      model.setProperty("/myItems", this._currentItems, /*context*/null, /*async*/true);
      return promise.resolve(); // continue closing dialog
    }
    
    function onAfterClose(event) {
      handleAfterClose(event.getSource(), this.byId("myList").getBinding("items"));
    }
    
    function handleAfterClose(dialog, listBinding) {
      dialog.unbindElement(); // reset data
      dialog.setBusy(false);
      listBinding.resume();
    }
    
    function handleSubmit() {
      const dialog = this.byId("myDialog");
      if (!dialog.getBeginButton().getEnabled()) return; // something is wrong
      dialog.setBusy(true);
      if (!this._isStillRequesting) {
        this._isStillRequesting = true;
        /* send request */setTimeout(mySuccessHandler.bind(this), 3000)
      };
    }
    
    function mySuccessHandler(newKeyFromServer = createPseudoUniqueID()) {
      const dialog = this.byId("myDialog");
      this._isStillRequesting = false;
      if (!dialog.isOpen()/* request was aborted e.g. by pressing ESC */) {
        return; // exit early
      }
      const context = dialog.getBindingContext();
      const value = context.getProperty("value");
      dialog.getModel().setProperty(context.getPath("key"), newKeyFromServer);
      dialog.close();
      sap.ui.require([
        "sap/m/MessageToast"
      ], MT => window.requestAnimationFrame(() => MT.show(`${value} created`)));
    }

  },
}).then(view => view.placeAt("content"))));

<script id="sap-ui-bootstrap" src="https://ui5.sap.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core,sap.m"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-async="true"
  data-sap-ui-compatversion="edge"
  data-sap-ui-excludejquerycompat="true"
  data-sap-ui-xx-waitForTheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>

如上所述,绑定和解除绑定元素也适用于服务器端模型,例如 v2.ODataModel.

As explained above, binding and unbinding element also applies to server-side models such as v2.ODataModel.

  • ✅ 减少过载: 无需迭代所有现有控件.仅重置需要重置的那些自动重置.
  • ✅ 控件不可知: 不依赖控件特定的 API,例如 myInput.setValuemySwitch.setState 等.立>
  • ✅ 降低维护成本:无需在控制器中维护应用程序需要手动重置的模型属性列表.
  • ✅ Reduced overload: no need to iterate over all existing controls. Reset only those automatically that need to be reset.
  • ✅ Control agnostic: does not rely on control specific APIs such as myInput.setValue, mySwitch.setState, etc..
  • ✅ Reduced maintenance costs: no need to maintain list of model properties in controller that application needs to reset manually.

这篇关于如何有效地重置绑定控制值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆