简体   繁体   中英

How to trigger observer on child element when nested in dom-if Polymer

I am trying to retrieve updated data in a child Polymer element, but the data stays bound to the initialized value.

PARENT

<template is="dom-if" if="[[items.0]]">
  <child-el id="id_0" id-item="[[items.0.idItem]]"></child-el>
</template>

...

_updateChild () {
  if (this.items[0]) {
    this.shadowRoot.getElementById('id_0').idItem = this.items[0].idItem;
    this.shadowRoot.getElementById('id_0').idItem.notifyPath;
  }
}

CHILD

<iron-ajax id="ajax"
  handle-as="json"
  last-response="{{data}}"
  method="get"
  on-error="_onError"
  url="https://api.com/item-price">
</iron-ajax>

<div>
  <p id="price">[[price(data.price)]]</p>
</div>

...

static get properties() {
  return {
    idItem: { type: String, observer: 'getResponse' }
  }
}

getResponse() {
  let request = this.$.ajax.generateRequest();
  request.completes.then(req => {
    this.idItem = null;
  })
}

price(amt) {
  return amt
}

Update pricing executes, but when idItem is set, but the observer on idItem " getResponse() " doesn't execute and bind to data.price .

How can I get these events to cascade properly so each time items.0.idItem changes the binding on the child-eel this.data.price gets updated?

How is the items.0.idItem changed?

Try changing the idItem like this this.set('items.0.idItem', 100)

Generally it is bad to re trigger something other than view with dom-if unless you don't use restamp attribute on it ( https://polymer-library.polymer-project.org/3.0/api/elements/dom-if#DomIf-property-restamp )

Your approach seems a little tricky, because after request is completed, you change observed property to null

getResponse() {
  let request = this.$.ajax.generateRequest();
  request.completes.then(req => {
    this.idItem = null;
  })
}

Changing it to null should result to re trigger observer again . But what will happen, is you just listen callback again, without re-triggering ajax request .

iron-ajax has method called generateRequest() , you probably should use it, if you don't have auto attribute set to iron-ajax component and don't change params of this component (see https://www.webcomponents.org/element/@polymer/iron-ajax/elements/iron-ajax#property-auto )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM