Observing an array that is initialised in the created lifecycle event - polymer

I have a working Polymer prototype, a code snippet of which is:
Polymer({
myData: [],
observe:{
myData: 'myDataChange'
},
myDataChange: function(val, newVal){ ... }
...
However, under the the attribute hinting section of the developer API, it states that objects and arrays should be initialised in the created lifecycle callback, not on the prototype. So, I changed the code snippet above to:
Polymer({
created: function(){
this.myData = [];
},
observe:{
myData: 'myDataChange'
},
myDataChange: function(val, newVal){ ... }
...
As soon as I make this change, the change watcher function no long invokes.
The myData property of my element instance is being populated by jQuery in an document ready callback. Moving this code into a 'polymer-ready' callback on the containing page solves this issue.
My concern with this is that my pages are going to be littered with polymer-ready events for the initial data population.
I amended my prototype so that the custom element is added to the DOM after a 5 second timeout, after the polymer-ready event was fired. Injecting the DOM like this doesn't fire the polymer ready event again.
Is this the correct/best approach to initialising properties on a Polymer element? I could manually fire an event from my custom element to say its loaded but this seems a bit crude. Any better ideas?

You shouldn't use any custom element before polymer-ready event (unless you're doing it intentionally), I think the best you could do is to replace every ready callback with polymer-ready.
However if you still want to use ready callback you could call myDataChange inside the element's ready callback:
Polymer({
created: function(){
this.myData = [];
},
observe:{
myData: 'myDataChange'
},
ready: function() {
this.myDataChange([], this.myData);
},
myDataChange: function(val, newVal){ ... }
....

Related

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.

Polymer. Way to dynamically add or remove observer

Is there a way to add or remove observer not in the moment of element initing?
I can define observer this way:
observers: ['dataChanged(data.*)']
Can i remove this observer later or can I set this observer different way than that?
You can easily add an observer dynamically, either by:
this._addObserverEffect("property", observerFunction);
or
this._addComplexObserverEffect("dataChanged(data.*)");
Removing is harder and Polymer does not provide a function to do this. Although you could search for it in the _propertyEffects array, I wouldn't recommend it. Maybe just check in your observer function whether it should still be active, and return if not.
you maybe can try this way:
configure your data property in the element with notify: true, so you can add a listener to changes with plain js
var element=document.querySelector("#YOUR-ELE-ID");
element.addEventListener("data-changed", function(e) {
//triggered when data property changes
});
https://www.polymer-project.org/1.0/docs/devguide/properties#notify
and to remove the bound listener you can call removeEventListener
https://developer.mozilla.org/de/docs/Web/API/EventTarget/removeEventListener
Example 1 - plain JS :
document.addEventListener('WebComponentsReady', function(e) {
var element=document.querySelector("#YOUR-ELE-ID");
element.addEventListener("data-changed", function(e) {
//triggered when data property changes
});
});
Example 2 - in custom element:
//...element definition...
ready: function() {
var element=document.querySelector("#YOUR-ELE-ID");
element.addEventListener("data-changed", function(e) {
//triggered when data property changes
});
}

Passing a function as an attribute value

I was wondering if it was possible to pass a function foo() as an attribute func="foo()" and have it called this.func() inside of the polymer element?
<foo-bar func="foo()"></foo-bar>
Polymer({
is: 'foo-bar',
properties: {
func: Object,
},
ready: function() {
this.func();
}
});
I've been trying to get this working for ages with no luck.
Thanks in advance.
<foo-bar func="foo()"></foo-bar>
Polymer({
is: 'foo-bar',
properties: {
func: {
type: String, // the function call is passed in as a string
notify: true
},
attached: function() {
if (this.func) {
this.callFunc = new Function('return '+ this.func);
this.callFunc(); // can now be called here or elsewhere in the Polymer object
}
});
So the trick is that "foo( )" is a string when you first pass it to the Polymer element. I fought with this for a while as well and this is the only way I could find to get it done. This solution creates a function that returns your function call, which you assign as the value of one of your polymer element properties.
Some people might say you shouldn't use the Function constructor because it is similar to eval( ) and.... well you know, the whole 'eval is evil' thing. But if you're just using it to return a call to another function and you understand the scope implications then I think this could be an appropriate use-case. If I'm wrong I'm sure someone will let us know!
Here's a link to a nice SO answer about the differences between eval( ) and the Function constructor in case it can help: https://stackoverflow.com/a/4599946/2629361
Lastly, I put this in the 'attached' lifecycle event to be on the safe side because it occurs later than 'ready'. I'm not sure if an earlier lifecycle event or 'ready' could be used instead of 'attached'. Perhaps someone can improve this answer and let us know.

Parent element is ready before its child - Polymer 1.0

This question had been modified to match the actual problem.
The original question mistakingly focused on iron-ajax, please see the original problem below. The question should have been:
Please advice why child iron-ajax element is not ready during the 'ready' callback of my-component defined as follows:
<dom-module id="my-component">
<template>
<link rel="import" href="../../../bower_components/iron-ajax/iron-ajax.html">
<iron-ajax
id="selectionLoader"
url=""
method="GET"
handle-as="json"
debounce-duration="300"
last-response="{{ suggestedOptions }}"
last-error="{{ lastError }}"
verbose=true
>
</iron-ajax>
</template>
</dom-module>
<script>
(function () {
Polymer({
is : 'paper-select',
ready : function() {
console.log(this.$.selectionLoader.generateRequest); // undefined
}
})
})()
</script>
Original question
Original title: 'WebComponentsReady' fires before iron-ajax ready - Polymer 1.0
I need to assign some values to an observed property of a custom component that internally uses iron-ajax with disabled auto - so I need to call .generateRequest on the iron-ajax element. This should happen when host page/component is ready, in order to fetch from the server some defaults based on data in the host component code.
selected is an array property on the component observed like this:
observers: [
'_selectedChanged(selected.splices)' // _selectedChanged calls .generateRequest
]
The observer is triggered by:
window.addEventListener('WebComponentsReady', function() {
document.querySelector('paper-select').selected = [{id : 11855},{id : 11856}];
});
The problem is that WebComponentsReady fires before .generateRequest is available on the iron-ajax. So my component is initialized, _selectedChanged is called, but iron-ajax inside it is missing the method and in fact other properties/methods as well.
I've implemented a "deferred" workaround using setTimeout inside the component and it works like charm but it's obviously not the way. Also everything works if the observer is triggered some time later after the page load, e.g. by user's typing. This shows that the logic works, it's just the timing that is wrong.
What am I missing?
The real issue was having the html imports inside my component's <template>.
The 'wrong' order of events makes sense as iron-ajax is not even registered at the time when its host calls the 'ready' callback.
I've moved the imports outside <dom-module> and now everything works as expected.

getting the value of a code-mirror element

I am using the code-mirror component from the Polymer Designer, and can set the initial value, but cannot see how to get changes to the code from the user.
I initialise the code-mirror using
<code-mirror id="code_mirror" value="{{code}}">
</code-mirror>
and would like to listen for changes in {{code}}, but codeChanged doesn't seem to fire.
I know I can get the actual value using code_mirror.$.mirror.getValue(), but would like to use data-binding.
I have tried using on-change to no avail.
Assuming you're using https://github.com/PolymerLabs/code-mirror what you need to do is make the CodeMirror instance created in the ready handle some events that the instance itself is emitting, then make the code-mirror element fire any custom event (something which I know is called event relay)
The following example makes the polymer element fire the custom event code-change whenever the editor value is changed
ready: function() {
var me = this;
//...
this.mirror = CodeMirror(this.shadowRoot, { /* ... */ });
this.mirror.on('change', function () {
// me = polymer instance
me.fire('code-change', { value: me.mirror.getValue() })
});
}
Then any instance of the polymer custom element would need to listen to that event using Polymer's declarative event mapping or through addEventListener
1st case (if code-mirror is inside another <polymer-element />):
<code-mirror on-code-change="{{ onCodeChange }}"></code-mirror>
// ...
<script>
Polymer({
onCodeChange: function(event, detail, sender) { ... }
});
</script>
2nd case ():
<code-mirror></code-mirror>
<script>
document
.querySelector('code-mirror')
.addEventListener('code-change', function () { ... });
</script>