Reputation: 1093
Recently I encountered the following problem:
In my Polymer-based project I have a custom element, let's call it <test-element>
. This element as px-rangepicker
as a dependency, which is basically just a date picker. If you select a date from that picker, the event px-datetime-range-submitted
is fired. Inside my test-element
I have a listener for that:
Polymer({
is: 'test-element',
properties: {
test: {
type: String,
value: "foobar"
}
},
listeners: {
'px-datetime-range-submitted': '_onDateRangeChanged'
},
_onDateRangeChanged: function(changeEvent) {
console.log(this.test);
}
});
Now, when I enter the site and test-element
is loaded for the first time, the _onDateRangeChanged
method is called. So far everything is okay. But:
Console just sais undefined
. No property is accessible from inside that method. The strange thing is:
console.log(Polymer.dom(this));
will give me a complete DomApi
output as expected, with my property as a node:
▼ DomApi {node: test-element}
▼ node:test-element.iron-selected
► $: Object
test: "foobar"
I can't help how this can happen - any help or info is highly appreciated.
Thank you.
Update:
See the code at GitHub and a working example here (the px-datetime-range-submitted
event is called 5 times and console output is undefined
).
Upvotes: 1
Views: 319
Reputation: 1259
Hi by your given example the problem is not your code or the code of the datepicker. Its just how polymer works.
Why does this happen?
The px-rangepicker implements a behavior called px-datetime-range-behavior within it there is an observer _notifyRangeChanged(range.*)
which gets triggered by a change of the range property also this observer fires the px-datetime-range-submitted
event. This property has a default value which means that its value gets filled at creation time of the component and also triggers the observer. And that seems to be done before the properties of your own component are initialized which then is still undefined. But after that when you open the picker and choose another date its triggered again and then the test property is filled with foobar
.
To prevent anything bad happening just check if the value of test is set.
_onDateRangeChanged: function(changeEvent) {
if(this.test !== undefined) {
console.log(this.test);
}
}
Upvotes: 2