Search code examples
javascriptpolymerdom-eventsweb-component

polymer event not fired


product-catalog.html

<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/paper-card/paper-card.html">
<link rel="import" href="/bower_components/paper-button/paper-button.html">
<link rel="import" href="/bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import"
  href="/bower_components/iron-icons/image-icons.html">
<link rel="import"
  href="/bower_components/iron-icons/iron-icons.html">
<link rel="import"
  href="/bower_components/iron-icons/social-icons.html">
<link rel="import" href="/bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="/bower_components/paper-toast/paper-toast.html">

<dom-module id="product-catalog">
	<template>
		<style>

      /* Make all toolbar titles in this host green by default */
      :host paper-card {
    	--paper-card-header-image: {
        	width:200px;
        	height: 350px;
        	margin: 0 auto;
    	};
    	--paper-card-header:{
    		font-family: Impact;
    		text-align: center;
    	};
	};
	paper-icon-button.pink {
    color: var(--paper-pink-500);
  };
  paper-icon-button.blue {
  	color: var(--paper-light-blue-500);
  };
  paper-icon-button.orange {
  	color: var(--paper-orange-500);
  };
  paper-button.cart {
  	font-family: Impact;
  };
  .yellow-button {
    text-transform: none;
    color: #eeff41;
  };
    </style>
        <iron-ajax
        id="AjaxGet"
        url=""
        method="GET"
        headers='{"X-Domain": "fashion","Accept-Language":"it","X-Country-Code":"IT","Accept":"application/stentle.api-v0.1+json"}'
        handle-as="json"
        on-response="_handleAjaxGetResponse"
        on-error="_handleAjaxGetError"
        ></iron-ajax>

        <iron-ajax
        id="AjaxPost"
        url=""
        method="POST"
        headers='{"X-Domain": "fashion","Accept-Language":"it","X-Country-Code":"IT","Accept":"application/stentle.api-v0.1+json"}'
        content-type="application/json"
        body = ""
        handle-as="json"
        on-response="_handleAjaxPostResponse"
        on-error="_handleAjaxPostError"
        ></iron-ajax>


		<paper-card heading="{{productName}}" image="{{productCover}}" alt="{{productName}}" >

  <div class="card-actions">
    <paper-button class="cart" raised on-click="addToCart">Add to cart</paper-button>
    <paper-icon-button class="pink" alt="amami" icon="favorite"></paper-icon-button>
    <paper-icon-button class="orange" alt="wishlist" icon="bookmark"></paper-icon-button>
    <paper-icon-button class="blue" alt="condividi" icon="social:share"></paper-icon-button>
  </div>
</paper-card>
	</template>
	<script>
	Polymer({
		is : 'product-catalog',
		properties:{
			productId : String,
			isStandAlone : Boolean
		},
    listeners: {
            'productAddedToCart': '_updateContent'
    },
    _updateContent: function () {
            console.log('Product catalog updated');
    },
    addToCart : function(){
      var productId = this.getAttribute('product-id');
      var baseUrl = "";
      if(this.cartId){
        this.$.AjaxPost.url = baseUrl + this.cartId+'/products';
        this.$.AjaxPost.body = 
          {
            id : productId,
            requestedQuantity : 1
          };
      }else{
        this.$.AjaxPost.url = baseUrl;
        this.$.AjaxPost.body = {
          productCartList:[
            {
              id : productId,
              requestedQuantity : 1
            }
          ]
        };
      }
      this.$.AjaxPost.generateRequest();
    },
		ready: function(){
			var productId = this.getAttribute('product-id');
			var isStandAlone = this.getAttribute('is-standalone');
			if(isStandAlone){
				this.$.AjaxGet.url = "";
				this.$.AjaxGet.generateRequest();
			}
		},
		_handleAjaxGetResponse: function (data) {
			var result = data.detail.response.data;
            this.productName = result.name;
            var imagesArray = result.photoGallery.images;
            for (var i = 0; i < imagesArray.length; i++) {
            	if(imagesArray[i].type==='cover'){
            		this.productCover = imagesArray[i].imageURL;
            	}
            };
            this.productDescription = result.description;
        },
      _handleAjaxGetError: function (data) {
            this.productName = '';
				this.productCover = 'http://i01.i.aliimg.com/wsphoto/v0/509741225/Free-shipping-Autumn-Spring-Winter-New-British-men-casual-shoes-everyday-casual-shoes-fashion-shoes.jpg';
				this.productDescription = '';
      },
      _handleAjaxPostResponse: function (data) {
			   this.cartId = data.detail.response.data.id;
         this.fire('productAddedToCart', {cartId: this.cartId});
      },
      _handleAjaxPostError: function (data) {
            console.log('ko cart');
      }
	});
	</script>
</dom-module>

cart-button.html

<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="/bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="/bower_components/paper-badge/paper-badge.html">

<dom-module id="cart-button">
    <iron-ajax
        id="AjaxGet"
        url=""
        method="GET"
        headers='{"X-Domain": "fashion","Accept-Language":"it","X-Country-Code":"IT","Accept":"application/stentle.api-v0.1+json"}'
        handle-as="json"
        on-response="_handleAjaxGetResponse"
        on-error="_handleAjaxGetError"
        ></iron-ajax>
<template>
            <paper-icon-button id="cart-icon" icon="shopping-cart" aria-label="Shopping cart: 0 items" role="button" tabindex="0" aria-disabled="false"></paper-icon-button>
            <paper-badge for="cart-icon" label="{{cartItems}}"></paper-badge>
            <paper-toast id="toast1" duration="0" text="{{productName}} in carrello.">
  		<paper-button onclick="document.querySelector('#toast1').toggle()" class="yellow-button">Continua lo shopping!</paper-button>
  		<paper-button onclick="document.querySelector('#toast1').toggle()" class="yellow-button">Vai al checkout!</paper-button>
	</paper-toast>
</template>
<script>
	Polymer({
		is : 'cart-button',
		properties:{
			customerId : String
		},
        listeners: {
            'productAddedToCart': '_updateContent'
        },
        _updateContent: function () {
            console.log('Cart button get updated');
        },
		ready: function(){
			var customerId = this.getAttribute('customer-id');
            this.cartItems = 0;
		},
        _handleAjaxGetResponse: function (data) {
            var result = data.detail.response.data;
            this.cartItems =result.productCart.length;
        },
	});
	</script>
</dom-module>

index.html

<!DOCTYPE html>
<html>
<head>
        <script src="bower_components/webcomponentsjs/webcomponents.min.js"></script>
        <link rel="import" href="bower_components/polymer/polymer.html">
        <link rel="import" href="product-catalog.html">
        <link rel="import" href="cart-button.html">
        <style>
.flex-container {
    display: -webkit-flex;
    display: flex;
    -webkit-flex-flow: row wrap;
    flex-flow: row wrap;
    text-align: center;
}

.flex-container > * {
    padding: 15px;
    -webkit-flex: 1 100%;
    flex: 1 100%;
}
</style>
</head>
<body>
	<div class="flex-container">
	<header>
		<cart-button></cart-button>
	</header>
	<section>
		<product-catalog product-id="5773d805d2453aed6a9e61e3" is-standalone="true"></product-catalog>
    	<product-catalog product-id="5773f17ad2453aed6a9e6205" is-standalone="true"></product-catalog>
    	<product-catalog product-id="5774046bd2453aed6a9e6211" is-standalone="true"></product-catalog>
    	<product-catalog product-id="577641a3d2453afd53c10b81" is-standalone="true"></product-catalog>
	</section>
</div>
</body>
</html>

I'm new to Polymer.

I try to handle an event fired in product-catalog element in cart-button element.

I attached a listener with listeners: {'productAddedToCart': '_updateContent'} but it doesn't work.

Is this wrong? Is there any other way or a best practice to share informations between component?


Solution

  • Event listener is not working because both elements are at the same level. So, one way to listen that event would be:

    // in ready function in cart-button element 
    this.listen(window, "productAddedToCart", "_updateContent"); 
    //(I don't like this way, but how you structured your elements this should work)