簡體   English   中英

Aurelia綁定鈎子在自定義元素中的“嵌套”數據更新

[英]Aurelia binding hook on “nested” data update in custom element

當綁定對象發生更新時,我想收到通知。 這個插件http://plnkr.co/edit/7thr0V演示了我的問題。

更詳細:我通過bind [data.bind]將對象“data”傳遞給自定義元素。 如果我現在更新數據中的屬性,我希望,調用自定義元素中的“dataChanged”掛鈎。 如果我在自定義元素模板中顯示綁定數據對象的屬性,它會更新,因此綁定本身可以正常工作。

我的第二個責備是使用ObserverLocator,但它也不會觸發嵌套更新。

app.js中的對象:

this.data = {
  nested: {
    content: "Hello nested world!"
  }
};

綁定到自定義元素ce:

<require from="ce"></require>
<ce data.bind="data"></ce>

ce.js部分:

@bindable data;

constructor(observerLocator) {
  this.observerLocator = observerLocator;

  var subscription = this.observerLocator
        .getObserver(this, 'data')
        //.getObserver(this, 'data["nested"]["content"]') //Doesn't work
        //.getObserver(this, 'data.nested.content') //Doesn't work
        .subscribe(this.onChangeData);
}

onChangeData(newData, oldData) {
  console.log('data changed from ', oldData, newData);
}

dataChanged(d) {
    console.log("Changed", d);
}

ce模板部分:

${data.nested.content}

在app.js中,我以2個間隔更新數據對象。 每秒的第一個間隔編輯一個“嵌套”屬性。 每五秒鍾的第二個間隔將數據對象設置為新的。 在第二個間隔,鈎子和觀察者被調用,但我想知道,當第一個間隔做任何改變時。

setInterval(() => {
  this.data.nested.content += "!";
}, 1000);


setInterval(() => {
  this.data = {
  nested: {
    content: "Hello nested world No. " + this.counter++  + "!"
  }
};
}, 5000);

ObserverLocator是Aurelia的裸機API,用於觀察簡單的屬性更改和數組/映射/集變異。

有一個新的,更高級別的API,稱為BindingEngine ,可用於觀察復雜的表達式。

這是一個例子: https//gist.run?id = 868a7611952b2e40f350

ce.html

<template>
  ${data.nested.content}


  <!-- debug logging -->
  <h4>Observed Changes:</h4>
  <div repeat.for="change of changes"><pre><code>${change}</code></pre></div>
</template>

ce.js

import {
  bindable,
  BindingEngine,
  inject
} from "aurelia-framework";

@inject(BindingEngine)
export class Ce {
  @bindable data;

  changes = []; // debug logging

  constructor(bindingEngine) {
    this.bindingEngine = bindingEngine;
  }

  expressionChanged(newValue, oldValue) {
    // debug logging:
    this.changes.splice(0, 0, `expressionChanged: "${newValue}"`);
  }

  syncSubscription(subscribe) {
    if (this.subscription) {
      this.subscription.dispose();
      this.subscription = null;
    }
    if (subscribe && this.data) {
      let observer = this.bindingEngine.expressionObserver(this.data, 'nested.content');
      this.subscription = observer.subscribe(::this.expressionChanged);
    }
  }

  dataChanged(newValue, oldValue) {
    // subscribe to new data instance
    this.syncSubscription(true);

    // debug logging:
    this.changes.splice(0, 0, `dataChanged: ${JSON.stringify(newValue, null, 2)}`);
  }

  attached() {
    // subscribe
    this.syncSubscription(true);
  }

  detached() {
    // unsubscribe (avoid memory leaks)
    this.syncSubscription(false);
  }
}

為什么aurelia默認情況下不會觀察整個對象的變化?

在速度和記憶力方面過於昂貴,急切地觀察一切。 並非所有瀏覽器都支持object.observe。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM