Function after dom-repeat finished - polymer

I created new component in Polymer 2, inside that i will use 2 web components, component a for show name of div and lenght of components b who will run a dom-repeat inside this web component.
With that said, after dom-repeat finishes my code isn't working how i want.
I need to get lenght of components b after dom-repeat run finished to:
- Get lenght and put in my counter in component a
- Separate all components b in groups of 6 inside one div
I made some JQuery code in fiddle, and will put drop below, this worked with default div's, but when i put in ready method of my polymer element is returning 0, isn't waiting dom-repeat finish. I tried setTimeout but this doesn't worked too.
console.log('Init count');
var content = $('component-b').length;
console.log('Cards: ' + content);
var item = $('component-b');
for (var i = 0; i < item.length; i+=6){
item.slice(i, i+6).wrapAll('<div class="list"></div>');
}
var lists = $('.list').length;
console.log('Lists: ' + lists);
$('component-a').attr({
total:content
});
$('component-a').attr({
totalPages:lists
});
Here i will put how this is working now.
Component a have properties to show counter.
<template>
<div class="secao">
<h2>{{title}}</h2>
<component-a>
<template is="dom-repeat" items="{{products}}" as="product">
<component-b class="product" product-id="{{product.productID}}" image-src="{{product.imageSrc}}" href="{{product.href}}"
main-title="{{product.mainTitle}}" authors-text="{{product.author}}" price-discount-value="{{product.priceDiscount}}"
price-value="{{product.realPrice}}" avaliation-score="{{product.avaliationScore}}" flag="{{product.flag}}"></component-b>
</template>
</component-a>
</div>
</template>
That is the result showed in Firefox.
Init count
Cards: 0
Lists: 0
But my Array have 24 cards, and with that jquery code would be 4 lists

Related

Data Bindings across template tags

I'm wondering, is there a possibility to have databindings "out of" a template? Say I have a <template/>-Tag somewhere which I put into the slot of a different component - that component stamps it to its context. Then I want to bind data from the root element to the <template/>-Tag. Also, event bindings (on-x-changed) don't work, because you can't assign a function which is defined in the hosting component. Any ideas?
Example:
... host
{{boundData}}
<binding-component>
<template>
{{boundData}}
</template>
</binding-component>
I don't see changes when I observe boundData in the hosting component. Is there a way to get around this? Or is firing a custom event my only chance?
If you are looking for binding a property outside of polymer something like from index.html you may bind value with element. an example ; index.html
<dom-bind>
<template>
<binding-component bound-data="{{boundData}}"></binding-component>
</template>
</dom-bind>
<script>
// set a value a string, Number or Object etc.
// Optionally wrap this code into a listener ie;
// window.addEventListener('load', e=> { ...below code ... })
var boundData= document.querySelector('dom-bind');
boundData = {} //
</script>
Now in your binding-component element has a property as boundData
hope its helps or provide more code to understand better.
I've made it work the way dom-if does it, too. Like in dom-if (reference), I'm creating a Templatize-instance which then uses forwardHostProp to handle the "inside"-properties
this.__ctor = Templatize.templatize(template, this, {
mutableData: true,
forwardHostProp(prop, value) {
// handling item updates, item being the only property
// from within the binding component
// everything else is automatically bound by templatize
this.set(prop, value);
this.update(this.item);
},
});
this.__instance = new this.__ctor();
this.root.appendChild(this.__instance.root);
This all happens in connectedCallback.
Because the Templatize-instance is passed this, it's bound to the current context as well.
Good luck!

Pass data to another Polymer component

I am working on a dashboard, in which I have a search panel at the top (let's call it component A), where users can enter a query. The value of this input will change a lot of other components in the dashboard (not only components that are its direct descendants or siblings). I want to send the search value from component A to component B, which should then respond by performing some action with the input value.
I have tried a few things:
Directly calling the function in component B. Haven't been able to get that to work at all.
Manually setting B's local property value and using an observer to trigger a function call. I manager to set the value, but the observer does not trigger.
Using a global variable, which I can easily access across components, but I still can't trigger functions in specific components.
How can I best do this?
I'm relatively new to Polymer, so forgive me if my ideas aren't completely 'Polymerised' :)
Approach 1
<dom-module id="component-B">
<template>
</template>
<script>
Polymer({
is: 'component-B',
properties: {
id: '',
observer: '_idUpdate'
},
_idUpdate: function(){
console.log("HELLO");
}
});
</script>
</dom-module>
<dom-module id="component-A">
<template>
</template>
<script>
Polymer({
is: 'component-A',
idSearch: function() {
var id = this.$.search.value;
document.querySelector('component-B').properties.id = id;
},
});
</script>
</dom-module>
As you want to send data to multiple elements (which might not be siblings of the firing element) you can use any of these two methods
Use iron-signal to fire the signal and then in all the elements where you want the data use iron-signal tag to listen to the signal
<iron-signals on-iron-signal-<signal-name>="<function>"></iron-signals>
You can also use standard HTML method dispatchEvent to fire a signal and then add eventListeners in all the element where you want data.

Can't find node by id in dom-if template

After download Polymer Starter Kit, I included a dom-if template inside (nested) the dom-bind template in index.html to hide the entire UI when user is not authenticated. However, I can’t get dom-if elements using app.$$(‘#id’) feature.
I’m trying to access the paperDrawerPanel in the app.closeDrawer funcion (app.js)
app.closeDrawer = function () {
console.log(app.$$('#paperDrawerPanel')); //returns null
};
How can I access that element?
Edit 1
This is the html part:
...
<body unresolved>
<span id="browser-sync-binding"></span>
<template is="dom-bind" id="app">
<auth-login id="auth" user="{{user}}" is-authenticated="{{isAuthenticated}}"" location="https://i2bserver.firebaseio.com"></auth-login>
<template is="dom-if" if="{{isAuthenticated}}">
<paper-drawer-panel id="paperDrawerPanel" drawer-width="220px" responsive-width="1100px">
...
Edit 2
I guess in the moment that app.closeDrawer is called by the routing.html the dom-if elements should already be tamped.
Here is the code that call app.closeDrawer (routing.html from PSK):
function closeDrawer(ctx, next) {
app.closeDrawer();
next();
}
// Routes
page('*', scrollToTop, closeDrawer, function(ctx, next) {
next();
});
element.$$ queries inside the DOM scope of element. In your case, app is a template whose job is to stamp DOM into the enclosing scope (body).
Try document.querySelector('#paperDrawerPanel').
From the docs:
For locating dynamically-created nodes in your element’s local DOM, use the $$ method:
this.$$(selector)
$$ returns the first node in the local DOM that matches selector.
That means you have to add a # symbol to reference the element using its id. Your code
app.closeDrawer = function () {
console.log(app.$$('paperDrawerPanel')); //returns null
};
should work if written like this
app.closeDrawer = function () {
console.log(app.$$('#paperDrawerPanel'));
};

How to access content of dom-if inside a custom element?

In a custom element I want to access a span and append a child to it but all usual accessors give undefined:
<template>
<template is="dom-if" if="[[condition]]" restamp>
<span id="myspan"></span>
</template>
</template>
ready() {
var a = this.$.myspan; //<------- is undefined
var b = this.$$.myspan; //<------- is undefined
var c = document.getElementById("myspan"); //<------- is undefined
var d = this.$$("#myspan"); //<------- is undefined
}
How to access a span in this case?
UPDATE: here is plunk
The reason this didn't work inside the lifecycle callback without setTimeout or this.async is that right after attaching your element the dom-if template has not yet rendered. Upon attaching your element, Polymer calls the attached callback. However, when the value gets set on the the dom-if, an observer runs and debounces its own _render function. The debounce waits an amount of time to catch any other calls to it, and then it executes the ._render function and attaches the element to the DOM. In other words, when the attached callback runs, normally the dom-if template hasn't rendered yet.
The reason for this debounce is performance. If several changes were made within a very short span of time, this debounce prevents the template from rendering several times when the result we would care about is the end result.
Fortunately, dom-if provides a .render() method which allows you to make it render synchronously. All you need to do is add an id to your dom-if, switch to an attached callback and call like this:
<template>
<template id="someDomIf" is="dom-if" if="[[condition]]" restamp>
<span id="myspan"></span>
</template>
</template>
attached() {
this.$.someDomIf.render();
var c = document.getElementById("myspan"); //<------- should be defined
var d = this.$$("#myspan"); //<------- should be defined
}
Triggering a synchronous render on the dom-if shouldn't be a huge performance problem, since luckily your element should only be getting attached once.
Edit: As it turns it, this even works in a ready callback:
<template>
<template id="someDomIf" is="dom-if" if="[[condition]]" restamp>
<span id="myspan"></span>
</template>
</template>
ready() {
this.$.someDomIf.render();
var c = document.getElementById("myspan"); //<------- should be defined
var d = this.$$("#myspan"); //<------- should be defined
}
See this fork of your plunker:
http://plnkr.co/edit/u3richtnt4COpEfx1CSN?p=preview
Try to do it asynchronously in the attached method as follows, this method works:
attached: function(){
this.async(function(){
var d = this.$$("#myspan");
console.log(d);
},someTimeIfThereAreManyItemsToLoad);
}
The responses above only work if your condition is true initially. Please see my answer to your initial question that lead to this one :
https://stackoverflow.com/a/34137955/3085985
Not sure if you should mix in the .render-stuff from Dogs, but I still think the observer would be the right place for it as it otherwise does not work if condition is false initially.
As in Polymer documentation:
Note: Nodes created dynamically using data binding (including those in dom-repeat and dom-if templates) are not added to the this.$ hash. The hash includes only statically created local DOM nodes (that is, the nodes defined in the element’s outermost template).
You will need to use this.$$('#yourElementId");

Polymer - Updating Element

I'm learning Polymer. One item that is challenging me is updating the item of an array. I wish there was a CDN for Polymer so I could put together a fiddle. For now though, I have an element defined like this:
my-element.html
<dom-module id="my-element">
<button on-click="onLoadData">Load Data</button>
<button on-click="onTest1Click">Test 1</button>
<button on-click="onTest2Click">Test 2</button>
<template is="dom-repeat" items="[[ data ]]" as="element">
<div><span>[[ element.id ]]</span> - <span>[[ element.status ]]</span></div>
<template is="dom-repeat" items="[[ element.children ]]" as="child">
<div> <span>[[ child.id ]]</span> - <span>[[ child.status ]]</span></div>
</template>
</template>
</template>
<script>
Polymer({
is: 'my-element',
properties: {
data: {
type: Array,
value: function() {
return [];
}
}
},
onLoadData: function() {
// Generate some dummy data for the sake of illustration.
for (var i=1; i<=3; i++) {
var element = {
id: i,
state: 'Initialized',
description: ''
};
element.children = [];
for (var j=1; j<=5; j++) {
var child = {
id: i + '-' + j,
state: 'Initialized',
description: ''
}
element.children.push(child);
}
data.push(element);
}
},
// Setting an individual property value works
onTest1Click: function() {
this.set('data.0.children.0.state', 'data set');
},
// Setting an entire object value does NOT work.
onTest2Click: function() {
var c = this.data[0].children[0];
c.state = 'data set';
this.set('data.0.children.0', c);
}
});
</script>
</dom-module>
For some reason, if I update the property value of an array element (as shown in onTest1Click), the UI is updated properly. However, if I update an entire element (as shown in onTest2Click), the UI does NOT get updated. In my real problem, I'm updating multiple properties on an element. For that reason, I'm trying to update an array element and not just a property. Am I doing something wrong or misunderstanding something? Or, am I going to have to update each property value individually?
If you want to mutate an array, rather than just an object in an array (such as swapping out an entire element in an array), there are array mutation methods similar to this.set.
For example, this.splice('data.0.children', 0, 1, c) will remove the current item at the 0 index of the child array and replace it with a new one, which is what it appears you're trying to do. There's also this.shift, this.unshift, this.push and this.pop. These are all similar to their Array prototype counterparts.
One thing to note is that in your example, you're also not actually swapping out the entire object. When you grab the element from the array, mutate a field, and try and replace it with itself, you're not actually replacing it, so that doesn't actually trigger an update. And since the mutation of the field was done outside of Polymer's notification system, that also doesn't trigger an update. If you replace the item with an actual different object, it will work using splice.
https://jsbin.com/rapomiyaga/1/edit?html,output (This is a modified snapshot of Günter Zöchbauer's jsbin)
If you're not making a copy of the object/a completely new object, you'll want to update each field individually through this.set.
Yes, you are going to need to update each property value individually. When you call set, Polymer will go to the given path and check if the value has changed. If the value is an object it will compare the references (and not the subproperties). Since the object reference has not changed, it will not update the UI.