In Polymer 1.0 you can drop {{localPropFoo.bar}} and bar will be observed for changes if you use this.set('localPropFoo.bar', 'new value'); to update its value.
But what to do if you want to bind template to an external object which is out of your control? E.g., this {{window.globalFoo.bar}} won't be bound to bar changes because external code doesn't depend on Polymer and doesn't call this.set.
Demo on codepen
Using Object.observe manually requires extra code and doesn't work in FireFox (dirty checks of observe.js to the rescue).
I want to know what is the idiomatic way of data binding to external objects out of your control.
Polymer doesn't do observation out of the box, because:
Object.observe support is not ubiquitous and dirty checks are expensive.
Object.observe may be expensive on itself.
Supposed Solution
Catch changes yourself, call notifyPath, this.fire('global-foo-changed', {path: 'globalFoo.bar', value:...}, this.set and this.push.
They all dispatch corresponding non-bubbling (capturing) globalFoo-changed custom events (only when needed).
Why my global-foo-changed events affect only this element?
global-foo-changed events are capturing (non-bubbling).
Polymer elements listen for bubbling events by default.
For some reason these capturing listeners capture bubble events dispatched from the same element (not from its children). Demo on codepen.
You may patch polymer with this behavior (I don't understand how it works):
SharedGlobalsBehavior = {
properties: {
globalFoo: {
type: Object,
notify: true,
value: globalFoo
}
},
created: function() {
window.addEventListener('global-foo-changed', () => {
if (!event.detail || !event.detail.path)
return; // Property initialization.
this.notifyPath(event.detail.path, event.detail.value);
},/* if capturing */ true);
}
};
Why No Observation Out of the Box
...sometimes imperative code needs to change an object’s sub- properties directly. As we avoid more sophisticated observation mechanisms such as Object.observe or dirty-checking in order to achieve the best startup and runtime performance cross-platform for the most common use cases, changing an object’s sub-properties directly requires cooperation from the user.
Specifically, Polymer provides two methods that allow such changes to be notified to the system: notifyPath(path, value) and set(path, value), where path is a string identifying the path (relative to the host element).
Related
I've seen people adding the event listener on the "ready" function and others on "connectedCallback". My question is, what are the pros and cons of each place? On connected we are responsible to remove it; in ready, it will stay there, and I'm unsure if it is a problem.
Should I do this:
connectedCallback() {
super.connectedCallback();
this.addEventListener('click', this.myFunction.bind(this));
}
disconnectedCallback() {
super.disconnetedCallback();
this.removeEventListener('click', this.myFunction);
}
Or this:
ready() {
super.ready();
this.addEventListener('click', this.myFunction.bind(this));
}
Up until Polymer 1.x.whatever , the ready callback in the life cycle of an element, was called, once
the element registered its shadow DOM
any <content>'s were distributed
and then, post ready , attached was fired
So, you could possibly have used ready as a one time callback after everything was indeed ready
With Polymer 2.0 onwards, there have been contractual changes to how callbacks are fired, and
The ready callback no longer is guaranteed to execute after the new <slots> are distributed meaning, there is no surety that the ready itself will wait for content / light DOM distribution.
attached is now the new connectedCallback and is essentially useful for element level DOM manipulations such as setting attributes , appending children etc. This is a lifecycle change that happens after the slot nodes are distributed and the element itself is attached in the DOM hierarchy, but not necessarily after a paint.
SO, for any event that does not rely on any ::slotted content, use the ready callback
for anything that requires a knowledge of all distributed content along with the shadow DOM, use the connectedCallback
However, when possible, use the afterNextRender method of the super class Polymer , within your element's callback to add event listeners
these are what I could possibly think of.
All this and much more, if it helps, here
I haven't yet read about us having to remove an event listener from a lifecycle callback, or anything as such.
If you are referring to cases where, the element itself may be connected and disconnected dynamically / or in the flow of things,
And, with that in mind, you are adding an event listener on a global / native element within your element's life cycle callbacks ,
like attaching an event listener on the window inside your custom-element's ready or connectedCallback ,
Only in such cases, does polymer advise you to remove the event listener on disconnect
When I google "Knockout Google Maps" I find quite some KO-based Google Maps implementations. All of which I was able to find take the approach to use a custom binding handler whereas I originally intended to implement it as a Knockout component.
Examples:
http://www.codeproject.com/Articles/351298/KnockoutJS-and-Google-Maps-binding
http://www.hoonzis.com/knockoutjs-and-google-maps-binding/
https://github.com/manuel-guilbault/knockout.google.maps
Can anyone point me in the right direction why one would prefer a custom binding handler over a KO component here?
My planned use case is this:
I'm implementing a page with a list of address search results. The list so far is a KO component, each list entry is generated by another KO component which the list component repeatedly calls in a foreach binding. Next to this list of search results I need a google map showing the result entries also in the map. There will also be quite a lot of interaction between the list, the list entries and the map.
Here's what I've got so far:
var GMap = function () {
var self = this;
var initMap = function() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: 51.4387974, lng: 6.9922915}
});
};
initMap();
};
$(document).ready(function() {
ko.components.register('gmap', {
viewModel: GMap,
template: { element: 'gmap' }
});
ko.applyBindings();
});
#map {
height: 400px;
width: 600px;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.22"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<gmap></gmap>
<template id="gmap">
<div id="map"></div>
</template>
A component and a custom handler are completely different things.
Custom binding
Basically a custom binding have access to:
the HTML component where it's used
the bound value (expression supplied to the binding)
all the other bindings in the element
the binding context of the element, from which you can acces to $root, $parent, and so on
Its definition includes two functions:
init: that allows to do the initial setup, like initializing widgets, setting event handlers and so on
update: it's called after init. In that moment you can access properties (including observable properties) through the binding, all the element bindings, the context and so on. This creates subscriptios that will call update when any of the accessed observable changes.
So a custom binding shuld be used when you need to interact directly with the DOM element, for example to modify its properties, initialize widgets, subscribe to events and so on
Component
A component is completely different. When you define a componente you must define:
a template, which is a set of DOM elements, usually with bindings
a viewmodel (usually a constructor or a factory)
When you use the component:
the viewmodel is instanced
the template is loaded
the viewmodel is bound to the template
So, a componente allows to reuse viewmodels and templates
So, what's the difference?
A custom binding has direct access to the DOM elements, allowing to interact with them, subscribe to events, modify properties, and so on
A component is only a viewmodel, and a set of DOM elements with bindings to that particular viewmodel.
So, in the case of Google Maps, which needs to initialize a widget (the map) and interact with Map events, and respond to observable propèrties cahnges, you could never use a component, because the component doesn't allow the direct interaction with the DOM elements. (Remember is a bunch of HTML elements with bindings, and the corrresponding view model, whic can't include any logic to intercat with those elements).
A custom binding usually applies to a single element (althoug it could handle its children, like foreach). In the case of Google Maps you only need the element in which you'll show the map.
A component is usually a more or less complex set of DOM elements, which are not accesible "from the outside". The only communication with the main viewmodel is done through parameters. The component cannot directly interact with the DOM elements: it must do it via ko bindings.
So, for the case of Google Maps is clear that you need a custom binding.
It only makes sense to create a component when you want to modularize or reuse a set of DOM elements, and the related viewmodel, which can also include functionality like accessing web services (via AJAX), making computations (propbaly by using computed observables), and so on. For example, a shopping cart could be implemented using a component, which would include:
the DOM elements to show the items in the cart (probably an HTML table, and some controls)
controls to modify the cart content (for example for deleting elements, or changing quantities)
a viewmodel that show the total, the taxes and so on
functionality to store the cart for later, or pay for it (which could be ajax calls to services)
In this case the cart would have a viewmodel which would include the computed observables (to show the total and taxes), the functionality to remove items, or modify quantities, or store or pay, and so on. And a concrete set of DOM elements with bindings for this viewmodel, i.e. the HTML to show the cart and interact with it.
In the case of Google Maps a component could not be used without the help of a custom binding or with the hacky use of additional, non ko, scripts.
If you wanted to show a list of places beside a map, and modify that list, you could use a component, which would include a viewmodel with the list and related functionality, and a template including an element with the Google Maps custom binding. That would make sense: viewmodel + several elements.
Conclusion
This all means that a custom binding usually have a deep interaction with the bound DOM element, while a component has a higher level interaction with the elements, which must be done through bindings.
So, they play a role at a very different level. You cannot compare or interchange them.
If you insist on doing so, you could create a beast of a binding which behaves like a component, becasue you have full control on the elements, and full acces to the view model, but that's harder to implement than a component. And probably could do the other way round also in some esoteric way.
Binding
Binding, a custom or not, is a very simple concept that covers 2 things:
A property of a UI element changes, and thus it should update an object (ViewModel)
A property of the object (ViewModel) changes, and thus it should update the UI element.
From the above if only 1 implemented, it is called One Way Binding (because if you change the UI, it will update the object but not the other way around). If both 1 and 2 are implemented, it is called Two Way Binding.
So at any time if you think you need something to do that, you would need to use binding, custom binding if the framework does not have the binding you need.
Most likely, the maps you speak of needed something like above. And it actually did because the author says this in the first paragraph:
Concretely, you can learn how to make the maps marker part of the View and automatically change its position any time when the ViewModel behind changes.
See, the author talks about 2 above: When the ViewModel changes, change the position of UI element.
Component
A component is a concept of having a reusable item that may have a UI but not necessarily, and all the code needed to make it work packaged along with it. This way it can be reused. For example, it may simply be an input UI element that only allows numbers. All the code needed for it is packaged along with the UI element.
Now the code packaged along with it may code related to bindings. It may even have custom bindings if the framework they used did not have the binding they needed. In addition it may have additional code that has nothing to do with binding.
Furthermore, a component may have a single UI element or multiple. A good example of a component with multiple elements would be a message box.
In Conclusion
Bindings and Components are separate things. A component may have bindings within it or it may have other code to make it work or both.
In the case of the maps you speak of, they have only added a feature to it: To react to changes in the ViewModel. It is not a component because it is not self contained and reusable.
They could have done it using a component. However, if they did that and said it is a KO component, it may still have KO specific binding code packaged with it along with the ViewModel and all the UI elements needed.
I can get my <iron-meta> instance to work properly when using a static value. But when I bind the value to a dynamic variable (using {{}}) it <iron-meta> no longer behaves as expected.
Does <iron-meta> support binding its value to dynamic variables?
<iron-meta id="meta" key="info" value="foo/bar"></iron-meta> // works
<iron-meta id="meta" key="info" value="{{str}}"></iron-meta> // fails
Previous work
This question is a refinement of this question in order to clarify that the ONLY thing causing the problem is the change from a static string value to a dynamic string value binding. I was getting a lot of other suggesting that had nothing to do with the change from static to dynamic so I thought it might be best to rewrite the question to clarify that. But the entire code context is contained in the links there if that would help.
Alternative solutions
There has been some recent chatter about using <iron-localstorage>. Perhaps that is the best way to go for dynamic binding essentially creating global variables?
Yes, <iron-meta> does support binding to variables, but perhaps not in the way you think.
Example: http://plnkr.co/edit/QdNepDrg9b3eCTWF6oRO?p=preview
I looked through your code here, here, and here but I'm not entirely clear what your expectations are. Hopefully my attached repro might shed some light. I see you have declaratively bound <iron-meta id="meta" key="route" xvalue="foo-bar" value="{{route}}"></iron-meta> which is fine - when route changes, iron-meta's key="route" will update accordingly.
However, be aware that in Polymer 1.0, <iron-meta> is in essence a one-way bind from parent to child in the sense that you set a meta key value dynamically by binding to a property; but to get that value, you'll have to get it imperatively via iron-meta's byKey() method.
<iron-meta> is just a simple monostate pattern implementation without an in-built path notification mechanism. What this means is value changes do not propagate upwards. Therefore, doing something like
<!-- this does not work like the way you think -->
<iron-meta id="meta" key="foo" value="{{bar}}">
in order to get the value of foo, or listen to changes to foo, does not work. This behaves more like a setter, where you set the value of foo based on your data-bound property bar.
From what I gather, it seems that you're trying to implement some sort of global variable functionality. A monostate implementation used to work in Polymer 0.5, but not in 1.0. Unfortunately, until Google endorses a "best-practice" pattern for this, suggestions till-date seems a bit speculative to me. You might find this (Polymer 1.0 Global Variables) helpful.
I have had success using <iron-signals> to communicate global information. I know there is a warning in the <iron-signals> documentation that discourages its use for related elements, but when broadcasting a shared resource it seems just the thing. For example:
// source element
var db = SomeDB.init();
this.fire('iron-signal', { name: 'database', data: db });
<-- sink element -->
<iron-signals on-iron-signal-database="dbChange"></iron-signals>
class SinkElement {
dbChange(e, detail) {
this.db = detail;
this.db.getSomeData();
}
}
Given an element instance, how do I see how many observers it's maintaining?
I'm trying to figure if either of these implementations is more expensive.
Polymer({
fooChanged: function() {
this.bar = foo.baz;
}
}
Polymer({
computed: {
'bar': 'foo.baz'
}
}
I suspect they're equivalent (except that one is watching foo, the other is watching the path) but I want to be sure.
Internally, Polymer uses uses Node.bind() to bind the property changes.
It will use PathObserver to watch 'foo.baz' and of course, it's slower to watch a computed object like that versus a single attribute.
https://www.polymer-project.org/docs/polymer/node_bind.html
You can check all the event listeners in the chrome dev tools. Select the ID in the console and on the right you have the "event listeners" tab.
See:
Using Chrome, how to find who's binded to an event?
But I doubt this will show you anything performance wise. I think it is better to use the CPU profile in the profiles tab in the chrome dev tools.
Is it possible to extend the addEvent function in mootools to do something and also calls the normal addEvent method? Or if someone has a better way to do what I need I'm all years.
I have different 'click' handlers depending on which page I'm on the site. Also, there might be more than one on each page. I want to have every click on the page execute a piece of code, besides doing whatever that click listener will do. Adding that two lines on each of the handlers, would be a PITA to say the least, so I thought about overriding the addEvent that every time I add a 'click' listener it will create a new function executing the code and then calling the function.
Any idea how I could do it?
Whereas this is not impossible, it's a questionable practice--changing mootools internal apis. Unless you are well versed with mootools and follow dev direction on github and know your change won't break future compatibility, I would recommend against it.
The way I see it, you have two routes:
make a new Element method via implement that does your logic. eg: Element.addMyEvent that does your thing, then calls the normal element.addEvent after. this is preferable and has no real adverse effects (see above)
change the prototype directly. means you don't get to refactor any code and it will just work. this can mean others that get to work with your code will have difficulties following it as well as difficulties tracing/troubleshooting- think, somebody who knows mootools and the standard addEvent behaviour won't even think to check the prototypes if they get problems.
mootools 2.0 coming will likely INVALIDATE method 2 above if mootools moves away from Element.prototype modification in favour of a wrapper (for compatibility with other frameworks). Go back to method 1 :)
I think solution 1 is better and obvious.
as for 2: http://jsfiddle.net/dimitar/aTukP/
(function() {
// setup a proxy via the Element prototype.
var oldProto = Element.prototype.addEvent;
// you really need [Element, Document, Window] but this is fine.
Element.prototype.addEvent = function(type, fn, internal){
console.log("added " + type, this); // add new logic here. 'this' == element.
oldProto.apply(this, arguments);
};
})();
document.id("foo").addEvent("click", function(e) {
e.stop();
console.log("clicked");
console.log(e);
});
it is that simple. keep in mind Element.events also should go to document and window. also, this won't change the Events class mixin, for that you need to refactor Events.addEvent instead.