2

In my application, I intercept clicks on links and turn them into AJAX calls in order to achieve Single-Page-App-iness. In jQuery this looks something like this:

$('#main').on('click', 'a[href]', function(e) {
  if (e.which == 2 || e.metaKey) return; // don't capture new tab clicks
  /* stuff */
});

Recently, however, I have begun using Custom Elements and Shadow DOM. The above code doesn't work on a tags which are in shadow trees, as the click event gets retargeted to the shadow host.

Is it possible to make the above code to work in order to intercept click events that occur in a shadow tree? If not, what is a best practice to continue to achieve this functionality?

Note: I am using Polymer Platform to polyfill Web Components (though not full Polymer).

Yuri Sulyma
  • 393
  • 1
  • 12

3 Answers3

1

In Polymer ≥0.4.0 you can use the /deep/ combinator:

$('#main').on('click', '* /deep/ a[href]', function() {
  if (e.which == 2 || e.metaKey) return; // don't capture new tab clicks
  /* stuff */
});

Note: This technique should be used sparingly, as it's potentially mucking about in the implementation of all components, including some parts of the web platform like <video> tags.

Peter Burns
  • 44,401
  • 7
  • 38
  • 56
0

Instead of hacking around your existing structure to make it act like a single-page app, you might want to design it that way from the beginning. That will give you the most of Web Component's awesomeness. Here's a demo (and source) of a single-page app using Polymer. Even if you don't want to use Polymer, you can probably use flatiron-director yourself to accomplish the same thing.

CletusW
  • 3,890
  • 1
  • 27
  • 42
  • This is how I've been "designing it that way from the beginning" to be an SPA? Most of the page (including the custom elements) is user-generated content, so I can't control the markup. That demo doesn't work for me in Firefox. – Yuri Sulyma Jul 18 '14 at 03:44
  • Good point. If it's user-generated content, you might be stuck with Peter's answer. – CletusW Jul 18 '14 at 05:15
0

You probably want to use core-ajax to handle your ajax calls and some form of inter-components communication to update your custom element.

Community
  • 1
  • 1
Renaud
  • 4,569
  • 7
  • 41
  • 72
  • This isn't a question about Polymer. It's about ShadowDOM/Web Components, which are polyfilled by Polymer *Platform*. – Yuri Sulyma Jul 29 '14 at 01:46