简体   繁体   中英

Using dom-if in Polymer

dom-if is not working in the given code. The code is processing and in debugging it also returns true. But the template is not displaying!

Why the template is not displaying?

<template is="dom-repeat" items="[[persistedProducts]]" as="product">
  <template is="dom-if" if="{{isProductLiked(product)}}">
    <paper-button on-click="dislikeThisProduct" 
      title="Click to UnLike" class="title-rose">
      <iron-icon icon="icons:thumb-up" class="title-rose" style="width:28px; height:17px;"></iron-icon>
      Liked
    </paper-button>
  </template>
</template>

isProductLiked: function(product) {
  let uid = this.user.uid;

  //Add visitor/user details here..
  this.$.queryProductLikes.disabled = false;
  this.$.queryProductLikes.ref.child(product.$key).child(uid).on("value", function(snapshot) {
    if(snapshot.val() != null) {
      //Display Like - if Liked.
      if(snapshot.val().isLiked) {
        return true;
      }
      return false;
    } else {
      //Not Liked
      return false;
    }
  });
}

I think the problem is in the isProductLiked function:

this.$.queryProductLikes.ref.child(product.$key).child(uid).on("value", function(snapshot) {
  if (snapshot.val() != null) {
    if (snapshot.val().isLiked) {
      return true;
    }
    return false;
  } else {
    return false;
  }
});

You use an anonymous function here ( ... function(snapshot) { ... ), so when you return true or false you aren't returning in the isProductLiked function, but in this anonymous function.

Edit

I am not familiar with Firebase so these may or may not work:

Possible solution #1

  1. Query the product likes outside of the isProductLiked function.
  2. Set a property based on the result. (Lets call it productLikes for this example)
  3. Use this result in the dom-if like this: <template is="dom-if" if="{{isProductLiked(product, productLikes)}}">
  4. Modify the isProductLiked function to include the productLikes parameter and to handle the new logic.

The idea here is, to remove any async function call from the isProductLiked function.

Possible solution #2

Redesign the data storage and query, so the persistedProducts contains the likes too. So you could write the dom-if like this: <template is="dom-if" if="{{product.isLiked}}"> .

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