Imagine I want two views (polymer-elements) to share a model, how can this be achieved?
In Angular, the model would reside in a singleton service that is injected into the views, allowing both views to access the same data source.
I attempted to replicate this approach with Polymer using the following code:
<polymer-element name="view1">
<template>
<my-model></my-model>
...
</template>
...
</polymer-element>
<polymer-element name="view2">
<template>
<my-model></my-model>
...
</template>
...
</polymer-element>
This method appeals to me as it offers a declarative way of defining dependencies, resembling the functionality seen in <core-ajax>
and other built-in Polymer elements.
However, one challenge I face is needing to wait for the domReady
lifecycle callback before interacting with any element declared in the template. Currently, my initialization logic is held within this callback. The issue arises when this callback gets executed for each <my-model>
element declared, potentially initializing the model multiple times due to its presence in both <view1>
and <view2>
. To enforce the singleton pattern for my model, I must relocate the state outside of the element instance. Here's an example of how I achieve this:
<polymer-element name="my-model">
<script>
(function(){
// private shared state
var instances = [], registered;
var foo;
// element init logic
Polymer('my-model', {
domReady: function(){
if (registered === (registered=true)) return;
foo = 'something';
this.addEventListener('foo', function(){ foo += 'baz'; });
},
attached: function() { instances.push(this); },
detached: function(){
instances = instances.filter(function(instance){
return instance !== this;
}.bind(this));
},
update: doSomething,
get state() { return foo; }
});
function doSomething(){ foo += 'bar' }
})();
</script>
</polymer-element>
While this solution functions, it feels unconventional. Should I reconsider using <polymer-element>
for implementing the singleton pattern? Are models and services better suited for another framework instead of Polymer? How do Polymer core-elements manage to handle these scenarios?
[EDIT] Event listeners have been added to the initialization code above. They are only registered in one instance to prevent triggering multiple times across various instances. What happens if the instance where event handlers are defined is removed? Will this disrupt the asynchronous logic?