<iron-list id="list" class="flex" items="{{data}}" selected-item="{{selectedItem}}" x="[[itemChanged(selectedItem)]]" selection-enabled>
<template>
<div class$="[[_computedClass(selected)]]">
<span class="flex">test</span>
</div>
</template>
</iron-list>
The solution I am looking for is like a radio group where there is always one selection in the iron-list.
I tried
itemChanged: function() {
if (this.selectedItem) {
this.selected = this.$.list.items.indexOf(this.selectedItem);
} else {
if(this.selected != null) { this.$.list.selectItem(this.selected);}
}
},
This ends up in a Uncaught RangeError: Maximum call stack size exceeded.
Here's an implemenation of this behaviour:
<dom-module id="test-element">
<style>
.selected {
background: blue;
color: white;
}
iron-list {
height: 200px;
width:200px
}
</style>
<template>
<iron-list id="list" items="[[data]]" as="item" selection-enabled on-selected-item-changed="itemChanged">
<template>
<div class$="[[_computedClass(selected)]]">[[item.name]]</div>
</template>
</iron-list>
</template>
</dom-module>
<script>
Polymer({
is: "test-element",
properties: {
data: {type: Array,
notify: true,
value: function() { return [
{"name": "Bob"},
{"name": "Tim"},
{"name": "Mike"}
]
;}
},
last: Object
},
ready: function(){
this.last = this.data[0];
},
itemChanged: function(){
if (this.$.list.selectedItem === null) {
this.async(function(){
if (this.$.list.selectedItem === null) {
this.$.list.selectItem(this.last);
}
}.bind(this));
} else {
this.last = this.$.list.selectedItem;
}
},
_computedClass : function(selected) {
return selected? "selected": "";
}
});
</script>
The relevant bit is in the itemChangedchanged function.
One thing that made it tricky, is the fact that the iron-list will trigger two events for each selection. First, it will unselect the previously selected item and then select the new item. So in order to figure out if no new item is selected, you have to wait and see if a new selection event is triggered. That's what I'm using the async for. Then I also store a reference to the previously selected item in the last property. In case no new item is selected, I restore the selection to the last selection.
Related
I noticed that template/data-binding in Polymer doesn't seem to reflect when a array property is mutated (i.e. push()). Sample code below:
<body>
<dom-module id="my-element">
<template>
<pre>
[my-element]
myArray: [[jsonStringify(myArray)]]
</pre>
</template>
</dom-module>
<my-element id="elm"></my-element>
<button onclick="pushArray()">pushArray</button>
<button onclick="setArray()">setArray</button>
<script>
(function registerElements() {
Polymer({
is: 'my-element',
properties: {
myArray: {
type: Array,
value: function () {
return [];
}
}
},
pushArray: function(value) {
this.push('myArray', {id: value});
},
setArray: function(value) {
this.set('myArray', [{id: value}]);
},
jsonStringify: function(obj) {
return JSON.stringify(obj);
}
});
})();
function pushArray () {
var elm = document.querySelector('#elm');
elm.pushArray('Push');
}
function setArray () {
var elm = document.querySelector('#elm');
elm.setArray('Set');
}
</script>
</body>
Whenever I click the pushArray button, an item "Push" should be added in myArray, but it wasn't reflected in the template [[jsonStringify(myArray)]]. is this an expected behavior? Anyway to work around this?
The Array change observer is a bit tricky. In your code, by using myArray, you implicitly observe (only) the reference for the (whole) array, which only changes when you run setArray.
In order to overcome this, you must also use a deep observer, namely myArray.*. The correct code for your dom-module is therefore the following:
<dom-module id="my-element">
<template>
<pre>
[my-element]
myArray: [[jsonStringify(myArray, myArray.*)]]
</pre>
</template>
</dom-module>
Live demo: http://jsbin.com/yulivuwufu/1/edit?html,css,output
No other code changes are necessary.
how can I use dom-repeat to create different elements for iron-pages? something like this:
<template is="dom-repeat" items="{{pages}}">
<[[item.name]]></[[item.name]]>
</template>
...
pages: {
type: Array,
value() {
return [
{
"name": "element-a",
},
{
"name": "element-b",
},
{
"name": "element-c",
},
},
I'm using polymer 2.0.
since my comment had some interest, I put it as an answer.
The code examples will be in polymer 1.9 for now, I'll update my answer when I'll do the switch to 2.0 but the idea should be the same anyway
First you need a wrapper element, wich will be capable of creating another element dynamically from a property, and adding it to itself.
In my example the name of the element to create will be a property named type of a JSON object Data wich came from a database in XHR.
With a dynamically created element the binding won't work, so you have to do it by hand. That's what the _updateStatefunction is for, here it only update on one property but the idea is the same is there is more.
wrapper :
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../styles/shared-styles.html">
<dom-module id="element-wrapper">
<template></template>
<script>
Polymer({
is: 'element-wrapper',
properties: {
elementData: {
type: Object
},
saveFbPath: {
type: String
},
element: {
type: Object
},
formSubmitPressed: {
type: Boolean,
value: false
}
},
observers: [
'_updateState(elementData.*)'
],
attached: function () {
console.log("creating element : ", this.elementData);
this.async(function () {
this.element = this.create(this.elementData.type, {
"data": this.elementData
});
this.appendChild(this.element);
}.bind(this));
},
_updateState: function (elementData) {
if (typeof this.element !== "undefined") {
this.element.data = elementData.value;
console.log('Change captured', elementData);
}
}
});
</script>
</dom-module>
The this.element = this.create(this.elementData.type, {"data":this.elementData}); line is the one creating the element, first argument is the dom-modulename, and the second a JSON object wich will be binded to the properties of the element.
this.appendChild(this.element);will then add it to the dom
All this is in a this.async call for a smoother display
You then need a dom-repeat which will call this element, and give it the datas it need to create the dynamic ones.
Here is an example of an element-list but you don't necessary need a specific element for that, this logic can be in a bigger one.
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../styles/shared-styles.html">
<link rel="import" href="element-wrapper">
<dom-module id="element-list">
<template>
<style is="custom-style" include="shared-styles"></style>
<template is="dom-repeat" items="[[ datas ]]" initial-count="10" as="data">
<element-wrapper element-data="[[data]]"></element-wrapper>
</template>
</template>
<script>
Polymer({
is: 'element-list',
properties: {
datas: {
type: Array,
value: function () {
return [];
}
}
}
});
</script>
</dom-module>
This should do the trick :)
Polymer dom-repeat is not working as expected, when I add a new element to the Array dynamically, dom-repeat not displaying the value.
I am using the Polymer's array mutation methods when pushing items into the array, but still not working.
Please check the codepen link;
<dom-module id="wind-studio-widget">
<template>
<div on-tap='_addNewPad' style="cursor:pointer"><strong>Click Me</strong></div>
<template id="padListContainerId" is="dom-repeat" items="[[padList]]">
<p style="border:1px solid red"> <span>[[item.id]]</span></p>
</template>
</template>
</dom-module>
<script type="text/javascript">
Polymer({
is: 'wind-studio-widget',
properties: {
baseUrl: {type: String},
padList: {
type: Array,
notify: true
},
padListAverage: {type: Object}
},
ready: function () {
//this.baseUrl = localStorage.baseUrl;
//this.loadPadData();
this.padList = [{'id':'1'},{'id':'2'}];
},
_addNewPad: function () {
var newPadList = this.padList;
newPadList.push({'id':'3'});
this.set('padList', []);
this.set('padList', newPadList);
console.log(this.padList);
//this.$.padListContainerId.render();
}
});
</script>
http://codepen.io/nareshchennuri/pen/vxjvdO
This is a common question in Polymer about updating view when model was updated (answer is to use this.set or this.push Polymer methods).
But when I have two elements:
First element:
properties:{
items: {
type: Array
}
},
someFunction: {
this.push('items', {'Name': 'something'});
}
Second Element has property which is bound to 'items' from first element
ready: function(){
this.items = firstElement.items;
}
I would like second element 'items' to be updated when 'items' updated on firstElement. I can't manually notify secondElement, because of app restrictions.
So for now I see (in devTools) that model of second element is correct ('items' contains objects), but view isn't updated.
How to update it?
You need to set notity on the property of the first element to receive changes outside of the element itself
properties:{
items: {
type: Array,
notify: true
}
},
then, in secondElement you can
<firstElement items="{{items}}" />
Let Polymer's two-way binding handle the notifications for you.
Consider two elements, x-foo and x-bar, in a container element, x-app.
In x-foo, declare items with notify:true so that its changes would be propagated upward.
Polymer({
is: 'x-foo',
properties: {
items: {
type: Array,
value: function() { return []; },
notify: true
}
}
});
In x-app, bind x-foo's items to x-bar's.
<dom-module id="x-app">
<template>
<x-foo items="{{items}}"></x-foo>
<x-bar items="[[items]]"></x-bar>
</template>
<script>
Polymer({ is: 'x-app' });
</script>
</dom-module>
Now, x-bar would be notified of all changes to the items array (when an item is added/removed).
HTMLImports.whenReady(() => {
"use strict";
Polymer({
is: 'x-app'
});
Polymer({
is: 'x-foo',
properties: {
items: {
type: Array,
value: function() { return []; },
notify: true
}
},
_addItem: function() {
this.push('items', {name: 'item' + this.items.length});
}
});
Polymer({
is: 'x-bar',
properties: {
items: {
type: Array
}
}
});
});
<head>
<base href="https://polygit.org/polymer+1.6.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
</head>
<body>
<x-app></x-app>
<dom-module id="x-app">
<template>
<x-foo items="{{items}}"></x-foo>
<x-bar items="[[items]]"></x-bar>
</template>
</dom-module>
<dom-module id="x-foo">
<template>
<h2><code>x-foo</code></h2>
<button on-tap="_addItem">Add item</button>
</template>
</dom-module>
<dom-module id="x-bar">
<template>
<h2><code>x-bar</code></h2>
<ul>
<template is="dom-repeat" items="[[items]]">
<li>[[item.name]]</li>
</template>
</ul>
</template>
</dom-module>
</body>
codepen
The current code is below. I have element-value in the main file. This value is passed to the child elements app-element and from there to app-element-add.
The value changes in app-element-add. But I cannot get the value reflected in the main element.
The observers never get invoked.
main.html
<app-element element-value = {{ elementValue }}></app-element>
Polymer({
is: 'app-main-element',
properties: {
elementValue: {
type:Array,
notify:true,
observer:'listUpdated'
}
});
app-element.html
<app-element-add element-value = {{ elementValue }}></app-element-add>
Polymer({
is: 'app-element',
properties: {
elementValue: {
type:Array,
notify:true,
observer:'listUpdated'
}
});
app-element-add.html
Polymer({
is: 'app-element-add',
properties: {
elementValue: {
type:Array,
notify:true,
reflectToAttribute:true
}
});
Any hints on how to reflect changes in app-element-add in app-main-element. Thanks.
You don't need to use reflectToAttribute here. The only option required here is notify. However, your current code works:
HTMLImports.whenReady(_ => {
"use strict";
Polymer({
is: 'app-main-element',
properties : {
elementValue: {
type: Array,
notify: true,
observer: 'listUpdated',
value: _ => [100,200,300]
}
},
listUpdated: function() {
console.log('[app-main-element] list updated');
},
ready: function() {
console.log('[app-main-element] ready');
}
});
Polymer({
is: 'app-element',
properties : {
elementValue: {
type: Array,
notify: true,
observer: 'listUpdated'
}
},
listUpdated: function() {
console.log('[app-element] list updated');
},
ready: function() {
console.log('[app-element] ready');
}
});
Polymer({
is: 'app-element-add',
properties : {
elementValue: {
type: Array,
notify: true
}
},
ready: function() {
console.log('[app-element-add] ready (will set elementValue in 1000ms)');
this.async(_ => {
console.log('[app-element-add] updating elementValue');
this.elementValue = [1,2,3];
}, 1000);
}
});
});
<head>
<base href="https://polygit.org/polymer+1.11.0/components/">
<script src="webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="polymer/polymer.html">
</head>
<body>
<app-main-element></app-main-element>
<dom-module id="app-main-element">
<template>
<app-element element-value={{elementValue}}></app-element>
<div>app-main-element.elementValue = [[elementValue]]</div>
</template>
</dom-module>
<dom-module id="app-element">
<template>
<app-element-add element-value={{elementValue}}></app-element-add>
<div>app-element.elementValue = [[elementValue]]</div>
</template>
</dom-module>
<dom-module id="app-element-add">
<template>
<div>app-element-add.elementValue = [[elementValue]]</div>
</template>
</dom-module>
</body>
codepen