Polymer 1.0
Is it possible to lazyRegister: max with:
1) nesting elements in parentmy-app element?
2) nesting elements in iron-pages?
I have a console.log statement in element single-listing that fires when attached is ran... which does it right away when the app loads. So, lazyRegister is not working for me.
<script>
// Setup Polymer options
window.Polymer = {
dom: 'shadow',
lazyRegister: 'max'
};
...
<my-app></my-app>
my-app.html:
<!-- Main content -->
<iron-pages attr-for-selected="data-route" selected="{{route}}">
<user-login data-route="user-login"></user-login>
<my-view1 data-route="my-view1" form-loading="{{isLoading}}"
listings="[[listings]]" tabindex="-1"></my-view1>
<single-listing data-route="single-listing"></single-listing>
<my-view3 data-route="my-view3"></my-view3>
</iron-pages>
single-listing.html:
attached: function() {
this.async(()=> {
console.log('foo') })
}
Is it possible to lazyRegister: max with nesting elements [...]?
Yes, this is possible, as can be seen in this Plunker.
Plunker note: There's a delay in Plunker before registering x-el, so wait a few seconds after "Hello world" appears before checking the console, which should display x-el attached:
lazyRegister is not working for me
I think you might be misunderstanding the purpose of that flag, and when registration occurs. The flag defers element registration until the element is created. You can create an element declaratively (i.e., by writing "<lazy-element>" in HTML) or imperatively (i.e., document.create('lazy-element'); in JavaScript).
In your example, you've declared the element, which effectively creates it, so the registration occurs when the host of the element is created. In the following example snippet, <lazy-element> is created when <my-app> is created, which is when <my-app>'s definition is imported.
<!-- my-app.html -->
<my-app>
<iron-pages>
<lazy-element></lazy-element>
</iron-pages>
</my-app>
If you want to defer element creation until the page is selected, you could lazy-load the element's import using one of the following methods (and remove lazyRegister flag, as it would be redundant):
this.importHref('lazy-element.html') (See how Polymer Starter Kit does it)
<iron-lazy-pages>
<lazy-imports>
Related
I am just trying out Polymer 1.0. I find that app-route/iron-pages is not working. Navigating between routes does not appear to show the correct view. Not sure which part went wrong:
In the main file:
<app-drawer-layout>
<app-location route="{{route}}"></app-location>
<app-route
route="{{route}}"
pattern="/:view"
data="{{routeData}}"
tail="{{subroute}}"></app-route>
<app-drawer>
<main-drawer></main-drawer>
</app-drawer>
<app-header-layout>
<app-header>
<paper-toolbar>
<paper-icon-button icon="menu" drawer-toggle></paper-icon-button>
<div class="title">
Expenses App
</div>
</paper-toolbar>
<iron-pages selected="[[view]]">
<expenses-dashboard name="dashboard" route="{{subroute}}"></expenses-dashboard>
<expenses-settings name="settings" route="{{subroute}}"></expenses-settings>
</iron-pages>
</app-header>
</app-header-layout>
</app-drawer-layout>
In side both expenses-dashboard and expenses-settings is just placeholder content like:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<dom-module id="expenses-dashboard">
<template>
<h1>Dashboard</h1>
</template>
<script>
Polymer({
is: 'expenses-dashboard'
});
</script>
</dom-module>
For <iron-pages selected="[[view]]">, should I be using routeData.view or view? I tried both didnt seem to change anything.
The code on GitHub
There are a few issues in your code...
Since your <iron-pages>.selected property is bound to an undefined property ("view"), <iron-pages> does not change its page. In your <app-route> data binding, the route parts are parsed into routeData, where the :view slug would be accessed with routeData.view, which is what you should be binding to <iron-pages>.selected:
<iron-pages selected="[[routeData.view]]">
The default selector for <iron-pages> is the page index (i.e., the child index of its contents), so selected would normally have to be an integer between 0 and N - 1 inclusively, where N is the number of child pages. But you could change that. It looks like you want the route to specify the page, which would need to match the name of a page under <iron-pages>. To use "name" as the selected attribute, you'd have to configure <iron-pages>.attrForSelected property:
<iron-pages selected="foo" attr-for-selected="name">
<div name="foo"></div>
<div name="bar"></div>
</iron-pages>
It might also be a good idea to specify a fallback selection, since the user could accidentally navigate to a URL that doesn't correspond to an existing page (e.g., https://mypage.com/#/non-existent-page).
<iron-pages selected="[[routeData.view]]" attr-for-selected="name" fallback-selection="foo">
<div name="foo"></div>
<div name="bar"></div>
</iron-pages>
In <main-drawer>, you may want to define menuTap() with ES5 syntax (instead of ES6) for maximum browser compatibility.
Polymer({
// menuTap(e) { ... } // <-- ES6
menuTap: function(e) { ... }
});
Your menuTap() function sets the window.location to a raw path, which noticeably refreshes the page. You could avoid the page refresh by using hash paths, where the intended sub-path of the URL is prefixed with a # (e.g., https://mypage.com/#/settings).
For hash paths, configure <app-location> to ignore the hash prefix by setting the useHashAsPath property:
<app-location use-hash-as-path route="{{route}}">
If you prefer to avoid hash paths, you could follow Polymer CLI's app-drawer-template, which uses anchor tags inside an <iron-selector> to set the location, which <app-location> detects and updates its route accordingly. Or you could pass the route in from <expenses-app> and then use this.set('route.path', "dashboard") inside of menuTap().
With the changes above, the following would occur when the user navigates to https://mypage.com/#/dashboard.
<app-location> would set the route property to /dashboard.
<app-route> would parse the route and set routeData.view to dashboard.
<iron-pages> sees routeData.view as dashboard, which matches the specified attribute on a child, which in turn causes only that page to be displayed.
For reference, the guide on Encapsulated Routing with Elements is quite useful.
Sorry if this comes out a bit garbled, I'm not sure how to ask this question.
What I am trying to do is keep the DOM synced with a localStorage value, and am updating the localStorage value with an interact.js mouse event.
Currently, I am able to properly set the localStorage value, but am having problems updating the DOM.
My current build is within the Polymer framework, so I am having trouble selecting shadow DOM content.
The DOM tree looks like
PARENT-ELEMENT
# SHADOW ROOT
EL
EL
DIV
CUSTOM ELEMENT
EL
EL
Here are some ways I have failed to solve the problem. The Custom Element is in pure JS, since I am not sure how to properly wrap interact.js function in Polymer:
I tried directly accessing the PARENT-ELEMENT's shadow DOM from the Custom Element in pure JS.
var shadowDOMNode = document.querySelector('PARENT-ELEMENT');
var dom_object_1 = shadowDOMNode.querySelector('#dom_object_1');
dom_object_1.innerHTML = localStorage.dom_object_1;
I tried selecting a helper updateDOM() function from the PARENT Polymer element and running it from the Custom Element's setter directly.
if (event.dy > 0) {
this.$$('PARENT-ELEMENT').updateDOM();
}
Maybe I am taking the wrong approach entirely, but I haven't been able to find analogues for interact.js in using native Polymer functions.
I hope this question was clear enough...
If we ignore the interact.js part of the problem and focus on Polymer, you could probably solve this without coupling the two.
To bind to a localStorage value with Polymer, use the <iron-localstorage> element. In the following example, the localStorage value named flavor_1_amount is loaded and stored into a property named _flavor1Amount. If the value doesn't exist in localStorage or is empty, the <iron-localstorage> element fires an event (iron-localstorage-load-empty), which allows you to bind to a callback (e.g., to initialize it).
<iron-localstorage name="flavor_1_amount"
value="{{_flavor1Amount}}"
use-raw
on-iron-localstorage-load-empty="_initFlavor1Amount">
</iron-localstorage>
In the same element, you could provide an input for the user to update the localStorage value.
<paper-input label="Flavor Amount (mL)" value="{{_flavor1Amount}}"></paper-input>
And you can use <iron-localstorage>.reload() to keep your data binding in sync, assuming it could be changed externally.
See this codepen for a full demo. Check your localStorage from Chrome DevTools:
Generally speaking you should use this.set() or any of the array mutation methods if it's an array in order for the ShadowDOM to be notified properly.
Since you want to perform this update from outside the element itself, imperatively, I'd suggest this:
Expose a couple of methods from your element that you can use to add/remove/change property values from outside your element.
These methods would internally use the proper channels to make the changes.
An example (you can call addItem() to add items from outside your element):
<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
<dom-module id="x-example">
<template>
<template is="dom-repeat" items="[[data]]">
<div>{{item.name}}</div>
</template>
</template>
<script>
HTMLImports.whenReady(function() {
"use strict";
Polymer({
is: "x-example",
properties: {
data: {
type: Array,
value: [
{name: "One"},
{name: "Two"},
{name: "Three"}
]
}
},
// Exposed publicly, grab the element and use this method
// to add your item
addItem: function(item) {
this.push("data", item);
}
});
});
</script>
</dom-module>
<x-example id="x-example-elem"></x-example>
<script>
setTimeout(function() {
// simply 'grab' the element and use the
// `addItem()` method you exposed publicly
// to add items to it.
document.querySelector("#x-example-elem").addItem({name: "Four"});
}, 2500);
</script>
Important: That being said, this is not the "Polymeric" way of doing stuff as this programming-style is imperative, in constrast with Polymer's style which is more declarative. The most Polymeric solution is to wrap your interact.js functionality in an element itself and use data-binding between your 2 elements to perform the changes.
I want to use Polymer's UI elements (e.g., iron-icons, paper-button, etc.) without making custom elements or templates.
For example, let's say I have:
<paper-button id="my-button">Click me</paper-button>
How do I listen for the 'click' event? Simply adding an event listener to 'click' for the ID 'my-button' doesn't work.
It should just work? I'm assuming you want to use Polymer UI elements in the main doc (index.html) without having to create any custom components. Say you have
<paper-button id="btn">Click me</paper-button>
in index.html. Via vanilla js,
document.querySelector("#btn").addEventListener("click", function (e) {...});
and via jQuery,
$("#btn").on("click", function (e, u) {...});
p/s: I'd write a quick jsbin as a demo, but rawgit seems to be having issues, and I'm not aware of alternative CDNs that host Polymer Elements.
Let me be clear: Polymer elements, and by extension web components, are designed to be framework-agnostic and, if properly coded, will work on their own - just like any other HTML element. Please do not dom-bind for the sake of dom-binding. You only do so if you a) require Polymer's sugaring (like data-binding) in your use-case; and b) you want to use Polymer's sugaring from your index.html - if you don't, please don't add additional complexity to your app.
I've found a cdn serving polymer elements, so:
Look, no dom-bind and elements are working with vanilla js.
Look, no dom-bind and elements are working with jQuery.
You can try:
<template is="dom-bind" id="t">
<paper-button id="my-button" on-click="buttonClicked">Click me</paper-button>
</template>
<script>
var template = document.querySelector('#t');
template.buttonClicked= function () {
alert("he clicked me :)");
};
</script>
$( "body" ).delegate( "#my-button", "click", function() {
alert();
});
Element needs some time for template-repeat to render all content, so paper-spinner is used to notify the user to wait.
How can I know that template-repeat has finished so I can turn off the spinner?
And related question: how can inner element "item-details" be selected? Again, template-repeat has to be finished first.
Here's the code I am using:
<polymer-element name="item-list">
<template>
<paper-spinner active></paper-spinner>
<template id="repeat_items" repeat="{{ item in car.items }}">
<item-details id="item_details" item="{{item}}"></item-details>
</template>....
This is some simulation of the problem: plnkr.co
Edit
links from research:
spinner example
why does onmutation disconnect after first mutation?
polymer-how-to-watch-for-change-in-content-properties
There are component lifecycle hooks.
You are probably looking for domReady.
Called when the element’s initial set of children are guaranteed to exist. This is an appropriate time to poke at the element’s parent or light DOM children. Another use is when you have sibling custom elements (e.g. they’re .innerHTML‘d together, at the same time). Before element A can use B’s API/properties, element B needs to be upgraded. The domReady callback ensures both elements exist.
Polymer('tag-name', {
domReady: function() {
// hide the spinner
// select the first item details element
}
});
As for selecting elements, you can traverse the component's shadow dom like so:
this.shadowRoot.querySelector(selector);
EDIT...
The domReady hook is great if you have all of your data up-front. If you get data asynchronously, then you can use a change watcher.
Here's is a fork of your plunkr that successfully selects the child components after the data changes. Notice the setTimeout(f, 1) that defers selection until after the DOM updates.
carsChanged: function(){
var _this = this;
setTimeout(function(){
console.log(_this.shadowRoot.querySelectorAll('item-details'))
},1)
}
I suggest something like this - http://jsbin.com/bifene/4/edit
Leverages Polymer's onMutation function to watch for changes to a DOM node. Note that it only gets called once so you'll need to re-register it every time you load new items & restart the spinner.
I'm using one of the core polymer components that basically has:
<polymer-element attributes="label">
<div>{{label}}</div>
as part of the source. I'd like to inject some HTML into this so that it ultimately renders as:
<div>Item <small>Description</small></div>
Is there any way to do this without copying the entire component (which is basically impossible considering the dependency chain)?
Polymer doesn't allow setting HTML inside {{}} expressions because it's a known XSS outlet. However, there are ways around it (1, 2).
I'm not sure there's a great way around this issue but I found something that works. You want to extend the element but also need to modify its shadow dom because of the .innerHTML limitation. Taking paper-button as an example, it has an internal {{label}}. You could extend the element, drill into its shadow dom, and set .innerHTML of the container where {{label}} is set. React to label changing (labelChanged) and call this.super():
<polymer-element name="x-el" extends="paper-button">
<template>
<shadow></shadow>
</template>
<script>
Polymer('x-el', {
labelChanged: function() {
// When label changes, find where it's set in paper-button
// and set the container's .innerHTML.
this.$.content.querySelector('span').innerHTML = this.label;
// call paper-button's labelChanged().
this.super();
}
});
</script>
</polymer-element>
Demo: http://jsbin.com/ripufoqu/1/edit
Problem is that it's brittle and requires you to know the internals of the element you're extending.