Polymer / polymer-starter-kit

A starting point for Polymer apps

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

odd event registration scoping

mrherndon opened this issue · comments

Description

This is an odd one so bear with me

starting with repro because it describes the issue well

Steps to reproduce

-first, create a fresh polymer 2 starter kit for the prpl-y goodness
-next, delete most of the my-app content, leaving it fairly bare-bones
-then drop in the bulk of the app-layout demo1.html, cause we like navigation
-load the page, click the menu button
-see the odd error that the target doesn't exist
-realize that it is looking for it in the wrong place
-pull out rest of hair

Expected outcome

Expect the side menu will open when the icon button is clicked

Actual outcome

an error is thrown because it is looking in the wrong scope for the element

Browsers Affected

only thought to check it in chrome

  • Chrome
  • Edge
  • Firefox
  • IE 11
  • Safari 8
  • Safari 9

Other thoughts

I tried this quite a few different ways trying to work out what's going on. I ended up creating a function in the element and an identically named one in the root index. Then I set the on-click to the function name.
I figured the error may have been hinting at a scope issue. The function in the root index is the one that fired. So when it is calling the elements function with onclick="startDrawer.toggle()" it is looking for startDrawer in the root index scope.
So, I don't know what is going on. And I hope I make any sense at all.

In app-layout demo1.html, startDrawer refers to the <app-drawer> element with id startDrawer - DOM defines variables for document-level element IDs. This doesn't happen in the scope of <my-app> though, so you'll need to write your own script. For example, the button element should be updated to:

on-click="_toggleDrawer"

Note the dash between on-click, since this is a Polymer-specific notation for binding to an event listener, not raw JavaScript.

Polymer({
  is: 'my-app',
 
  /* ... */

  _toggleDrawer: function() {
    this.$.startDrawer.toggle();
  }
});

Note this.$.startDrawer is a reference to the drawer in <my-app>'s scope - the this.$ notation is provided by Polymer.