代码之家  ›  专栏  ›  技术社区  ›  Tina Chen

如何在SAPUI5中实现数据绑定?

  •  3
  • Tina Chen  · 技术社区  · 6 年前

    在这个令人敬畏的问题中: How to Implement DOM Data Binding in JavaScript 许多数据绑定实现细节都得到了很好的解释。

    也有许多探索性的博客关于角度、对象的脏检查。定义Vue中使用的属性。js和虚拟DOM等等。。。

    但在 UI5 docs ,只有如何使用数据绑定。没有关于如何实现数据绑定的详细信息。

    我读过关于 sap.ui.base.ManagedObject source code of it .在 constructor of sap.ui.base.ManagedObject ,它说这些对象与数据绑定有关,但我不知道如何。有时我会注销它们以调试我的数据绑定,但仍然看不到全局:

            // data binding
            this.oModels = {};
            this.aPropagationListeners = [];
            this.oBindingContexts = {};
            this.mElementBindingContexts = {};
            this.mBindingInfos = {};
            this.mObjectBindingInfos = {};
    

    也迷失在 ManagedObject.prototype.bindObject

    我真的希望了解当数据模型改变时Dom是如何更新的,反之亦然。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Tina Chen    6 年前

    一些评论说UI5使用手柄进行数据绑定,搜索后,手柄只支持 one-time data binding .我更好奇的是 双向数据绑定 在UI5中实现(很抱歉没有首先明确说明这一点)。

    在HandleBars中,一旦编译了模板,视图/DOM与数据模型无关。

    但双向数据绑定将数据连接到其本地DOM中元素的属性或属性。这意味着:

    当模型中的属性更新时,UI也会更新。更新UI元素时,更改会传播回模型。 https://stackoverflow.com/a/13504965/5238583

    关于 How to Implement DOM Data Binding in JavaScript ,提到了许多技术。UI5使用了这两个(到目前为止我已经发现): add change event listener mutators(setter)

    我使用了这个官方示例: Data Binding - Step 13 - Element Binding

    数据绑定在 oProductDetailPanel.bindElement({ path: sPath, model: "products" }); 被调用。

    在中设置断点 oBinding.setContext() in ManagedObject.prototype.updateBindingContext ManagedObject.prototype.updateProperty 。您可以在调用堆栈中看到它。

    TL;DR:核心步骤是3、6、8

    主要步骤包括:

    1. Element.prototype.bindElement 等于 ManagedObject.prototype.bindObject

    2. oBinding.initialize() 也就是说 ClientContextBinding.prototype.initialize 已调用 ManagedObject.prototype._bindObject

    3. Binding.prototype._fireChange 在中调用 createBindingContext 回调。哪个火灾 change 事件: this.fireEvent("change", mArguments) ;

    4. 和更改事件处理程序在中定义 ManagedObject。原型_bindObject :

      var fChangeHandler = function(oEvent) {
           that.setElementBindingContext(oBinding.getBoundContext(), sModelName);
      };
      oBinding.attachChange(fChangeHandler);
      oBindingInfo.modelChangeHandler = fChangeHandler;
      
    5. setElementBindingContext() 呼叫 ManagedObject.prototype.updateBindingContext 最后

    6. 在里面 updateBindingContext ,调用堆栈为 oBinding.setContext(oContext) -&燃气轮机; JSONPropertyBinding.prototype.checkUpdate (因为这里的示例使用JSON模型)——> this._fireChange({reason: ChangeReason.Change})

    7. 对于第二个更改事件,处理程序位于 ManagedObject.prototype._bindProperty (有很多 fModelChangeHandler 在ManagedObject的绑定函数中 bindElement 样品,我们只需要这个)

    8. fModelChangeHandler ,则, ManagedObject.prototype.updateProperty 被调用。使用setter(mutator)的地方:

    每当更改属性绑定时。此方法从属性绑定获取外部格式,并将其应用于setter。

    this[oPropertyInfo._sMutator](oValue); .对于我们的样品 oPropertyInfo._sMutator setValue .执行此操作,输入中的值 <Input value="{products>ProductID}"/> 将被更改。

    此处的原始记录: https://github.com/TinaC/Blog/blob/master/SAPUI5/Data_Binding.md