The seminal British spy-fi series The Prisoner, which ran for 17 episodes in 1967–68, was an oddity that cast a long shadow, influencing many better-remembered weirdo TV series that came later, including Twin Peaks, The X-Files, and Lost. Each episode began with a lengthy title sequence wherein co-creator and star Patrick McGoohan’s unnamed character angrily resigns from some unspecified high-security job and is then gassed and abducted, waking up to a strange life in a surreal village he’ll spend the duration of the series trying to escape.
That’s also more or less the way the new Apple TV+ series Dark Matter begins, albeit with several caveats. For one thing, we’re privy to substantially more information about the character played by star and co-producer Joel Edgerton before he gets drugged and forcibly ejected from his day-to-day: His name is Jason Dessen and he teaches physics at Lakemont College, a fictional but undistinguished institution of higher learning. He’s married to gallery owner and triathlete Daniela, played by Jennifer Connelly, and they live in a gorgeous house in Chicago’s Logan Square neighborhood with their sensitive 15-year-old son, Charlie (Oakes Fegley). Finally, when Jason’s college pal Ryan (Jimmi Simpson), a neurologist, calls to say he’s won the Pavia Prize — a fictional but evidently very distinguished million-dollar science award — we intuit that Jason has occasionally second-guessed his long-ago decision to prioritize family life over his research. “It should be you,” Ryan tells him, suggesting it was Jason who was once poised for greatness.
So we have a reasonably complete dossier on Jason by the time he gets kidnapped by a masked man with a gun on his way home from the Village Tap — the un-fictitious and evidently well-loved Logan Square watering hole where he reluctantly joins Ryan’s Pavia Prize celebration one rainy night. That’s one major difference between Dark Matter and The Prisoner. Another one would be that the creators of Dark Matter almost certainly know where they’re going, as writer-producer Blake Crouch is adapting his eponymous 2016 novel. The Prisoner, by contrast, more or less disintegrated as it became apparent that star McGoohan, story editor George Markstein, and financier Lew Grade all had very different notions of what their show was about and how it should end. (My friend Glen Weldon and I did a whole podcast about it.) One of its most satisfying episodes was “Schizoid Man,” wherein McGoohan’s character faces off against his doppelgänger via some crisply executed Parent Trap–style split-screen gimmickry.
Those vaguely Prisoner-esque fingerprints are the main reason for my interest in Dark Matter, a thriller wherein Edgerton’s Jason is menaced by an alternate version of himself. Even within this pilot episode, Crouch and director Jakob Verbruggen make little effort to hide that Jason’s tormentor is, in fact, another Jason, trespassing from a dimension wherein he made different choices. Choices he’d now like to revise.
By the end of the 46-minute hour, Jason A and Jason B, let’s call them, will have gone full Freaky Friday on one another’s lives. A confused and terrified Jason A will flee some private medical facility where his colleagues — all strangers except for one Leighton Vance, whom this Jason hasn’t seen since college — tell him he’s just reappeared after a mysterious 14-month absence. Jason B, the architect of this trans-dimensional switcheroo, will make himself at home in Jason A’s house and marriage.
The pilot episode explores the duality of its premise in clever ways … and clumsy ones. I appreciated the early scene in which Jason allows Charlie to drive himself to school while Jason observes from the passenger seat. Charlie misses a red traffic light and almost plows into another car. As this happens, Jason asks Charlie if the boy has yet found a way to tell a girl named Brooke about his affection for her, gently advising his son that it’s unhealthy to keep one’s strong feelings secret for very long.
The clunkiest scene is a prime specimen of the Movie Classroom, wherein Jason explains the concept of Schrödinger’s cat to a dozen or so bored undergrads. The dismissal bell (in college?) rings before he can finish his explanation of superposition, so he throws it in as an afterthought as his pupils file out: The cat inside the box is at once alive and dead. Who are these physics students who’ve never heard of the most famous thought experiment in physics? Who is this professor who chooses to begin a lesson on this in the last 45 seconds of class?
Maybe we’re meant to intuit that Jason’s timing has always sucked. Edgerton, whose sunken-eyed good looks have always been an advantage when it comes to playing haunted dudes, fully sells Jason’s sadness and the guilt he feels for being unsatisfied with so rich a life. His career is going nowhere, but he has a loving family and a dope house in one of the world’s great cities.
That night, while Jason drinks wine and cooks pasta for his family, Charlie protests that his folks’ canoodling is “scarring [him] for life.” Jason’s phone blows up with texts from Ryan summoning him to the Village Tap. Only when Daniela asks what the occasion is does Jason share that their longtime pal has won the Pavia, which Daniela says is occasion enough to excuse Jason from family night. She even points out that Ryan’s choice of the Village Tap — a bar nearer to their home than his — is proof of how important Jason’s attendance is to Ryan, though she clearly intuits the jealousy Jason has yet to admit even to himself. “Don’t be a dick,” Daniela advises her spouse.
The Animals’ “We Gotta Get Out of This Place” is on the jukebox as Jason greets Ryan at the Village Tap. There’s a montage of Ryan’s other, more science-famous guests, all registering unfamiliarity as Jason introduces himself. Ryan’s largesse in buying his old pal an entire bottle of Macallan scotch — he asks for the bar’s best — is the sort of flex that seems to make Jason all the more conscious of the fact he’s a man on a budget.
The scotch won’t be Ryan’s only offering tonight. After the party quiets down a little, the two friends go to a booth. Jason asks his buddy to quote the citation from his Pavia Prize. “For his groundbreaking work in the field of neuroscience and identifying the prefrontal cortex as a consciousness generator,” Ryan recites.
So Ryan is a neuroscientist, which introduces some mystery when Ryan tells Jason, “I owe you. Those notes were essential.” Aren’t these guys in different disciplines? An admirer comes over to hit on Ryan, but he asks her to wait while he makes his pitch to his old pal. Ryan is starting a neurotech firm and wants to bring Jason aboard. “If you’re pinching yourself every morning on your way to Lakemont, then please tell me to fuck off,” Ryan says, promising to “crush” Jason’s meager salary. The job is in San Francisco, and Jason is reluctant to uproot his family. Ryan just asks that he talk it over with Daniela.
However, Jason is conflicted, declining to pick up a call from Daniela as he leaves the bar. So divided is his attention that he’s almost run over by a taxi. Suddenly, it’s raining, and a shift in lighting suggests that significant time has passed, but Jason still hasn’t found his way home.
It’s at this point that the assailant in a hood and a theatrical Eyes Wide Shut mask forces Jason into a vehicle at gunpoint. They drive past the Village Tap, where Ryan and his hookup are just leaving, so maybe it’s only a brief time later instead of several hours? The kidnapper seems to know all about Jason: He asks if his iPhone passcode is still his dad’s birthday in reverse and demands to know what Ryan wanted to talk to him about at the bar.
When they arrive at their dank, underlit destination, Jason attempts to overpower the assailant, and he manages to wound the guy in the arm, but he’s still defeated, losing strength when the masked man injects him with a sedative. The man then orders Jason to change into the clothing he’s provided, warning him he’ll pass out soon. The masked man is fiddling with a small box with a hinged lid; its glow suggests an electronic interior we cannot see. A stoned Jason A asks what the box is. “It’s, uh, possibility,” the masked man growls.
As Jason A’s last embers of awareness fade, the masked figure leans over him. “Are you happy with your life?” he asks. “Or have you ever wondered what else you could’ve been?” After a brief metaphysical pep talk, the masked man concludes, “I’m sorry, but I’m doing this for us. For both of us.”
“Who arrrrre yooooou?” Jason A slurs.
“You wouldn’t believe me if I told you,” the man replies.
When Jason A regains consciousness, he’s staring up at the light array above an operating table. “Test everything,” someone says. He cowers under a high-pressure shower, then wakes up again, this time in a locked and windowless room, alone. A woman — Alice Braga — knocks and enters, greeting him with a hug. She’s taken aback that he doesn’t know her, but introduces herself as Amanda. She tells him he’s been through a lot but that the good news is that he’s cleared to leave quarantine: there’s no trace of radiation or biohazards in his system.
She brings him to meet “Leighton,” whom Jason recognizes from long ago. (If the turtleneck and expensive wristwatch didn’t already peg Leighton as a tech CEO, the character is played by Dayo Okeniyi, whom even I did not recall played SkyNet inventor Danny Dyson in the unloved Terminator Genisys.) For the benefit of the camcorder in the room, she introduces herself as Amanda Lucas, staff psychiatrist. She identifies the men as Leighton Vance, CEO, and Jason Dessen, chief science officer. “You’re the only one who’s returned,” Leighton tells him. Amanda says he’s been away for 14 months and ten days.
Leighton asks Jason what he remembers. His hazy recollection of the night at the bar with Ryan — a name Leighton is surprised to hear — curdles into a panic when Amanda asks about cuts and bruises on his face, evidence of his dust-up with the man in the mask.
Jason bolts from the facility, throwing himself in front of a cab — intentionally this time — and asking the driver to take him home to Eleanor Street. But Jason doesn’t recognize his house when he arrives; the interior has changed. He does recognize the woman he finds there: It’s Amanda, who had greeted him with an embrace a short while earlier. But that doesn’t explain why she’s in his house or where his family and their belongings have gone. Amanda tells Jason A that she is the person with whom he shares this house, and she has no idea who Daniela or Charlie are. In what should be Charlie’s bedroom, Jason A finds a monument to his great achievements as a physicist, including a Pavia Prize inscribed with his name.
It’s roughly here that the episode adopts the irritating convention of signaling a switch among realities with a sound effect that resembles a Zippo lighter being flicked open. There’s a Zippo flick, and Jason B arrives “home” to find Daniela washing dishes and sulking that he’s ignored her messages all evening. He’d found a text from her on Jason A’s phone asking him to bring home ice cream, but Jason B seems not to know her preferred flavor. “Mint chocolate chip,” she says. “Really?”
When he kisses her, she asks him what the fuck is going on. He tells her about Ryan’s job offer, then asks her if she remembers what he said to her when they decided to marry. She says that he told her at the end of his life he’d rather have memories of her than of “a cold, sterile lab.”
“I stand by that today,” he says, melting away the last of her anger.
It’s another Zippo flick, and we’re back with Jason A and Amanda in their version of the same kitchen. Jason A hears a vehicle pull out outside, and he flees again.
The episode ends with defunct Chicago band Kids These Days’ “Don’t Harsh My Mellow” on the soundtrack as Jason B and Daniela tumble into bed with a renewed hunger. Daniela notices the wound on her husband’s arm and asks how he got it.
“You wouldn’t believe me if I told you,” he says again. Hey, try us.
General Relativity
• When Daniela kisses her husband and son good-bye on her way to work, she’s carrying an apple. She reacts with surprise and gratitude when Jason hands her a travel mug of coffee. Apples and coffee are two great tastes that do not taste great together.
• I want someone who drinks at the Village Tap in Logan Square, Chicago, to tell us if the bar really does have a neon sign that reads “Resilience” in one of its street-facing windows. Because that’s cool.
By submitting your email, you agree to our
Terms and Privacy Notice
and to receive email correspondence from us. This site is protected by reCAPTCHA and the Google
Privacy Policy and
Terms of Service apply.
or
Already a subscriber?
What is your email?
This email will be used to sign into all New York sites. By submitting your email, you agree to our Terms and Privacy Policy and to receive email correspondence from us.
Password must be at least 8 characters and contain:
Lower case letters (a-z)
Upper case letters (A-Z)
Numbers (0-9)
Special Characters (!@#$%^&*)
This password will be used to sign into all New York sites. By submitting your email, you agree to our Terms and Privacy Policy and to receive email correspondence from us.
You’re in!
As part of your account, you’ll receive occasional updates and offers from New York, which you can opt out of anytime.
or
Already a subscriber?
What is your email?
This email will be used to sign into all New York sites. By submitting your email, you agree to our Terms and Privacy Policy and to receive email correspondence from us.
Password must be at least 8 characters and contain:
Lower case letters (a-z)
Upper case letters (A-Z)
Numbers (0-9)
Special Characters (!@#$%^&*)
This password will be used to sign into all New York sites. By submitting your email, you agree to our Terms and Privacy Policy and to receive email correspondence from us.
You’re in!
As part of your account, you’ll receive occasional updates and offers from New York, which you can opt out of anytime.
Already a subscriber?
Already a subscriber?
`;
// integrate Sub(x) scripts and elements
if (hostname !== 'subs.nymag.com') { // do not integrate on this subdomain
document.head.appendChild(trackingScript);
document.body.insertAdjacentHTML('beforeend', subXAnimationElements);
}
There was an error processing the request. Please try again later."}).catch(e=>console.error("Error verifying email: ",e)))(r.querySelector(".content"),o.bannerCTAVerification)})):(l.remove(),s.remove()),o.dismissable||n.remove(),o.useAlertIcon||a.remove(),r.classList.add("show"),n.addEventListener("click",()=>{u(),r.classList.remove("show")})}else r.remove()}});
}, {"1":1,"6":6,"12":12,"35":35,"40":40}];
window.modules["global-nav.client"] = [function(require,module,exports){"use strict";const dom=require(3),auth=require(12),signInButton=dom.find(".user-signin"),signOutButton=dom.find(".user-signout"),globalNav=dom.find('[class^="global-nav"]'),body=dom.find("body"),dropdownItems=dom.findAll(".dropdown-wrap"),gtm=require(1),appendLandingPageParams=require(136),pageUri=require(124).getPageUri(),subscriptionPromoLinks=dom.findAll(".persist-params"),searchString=window.location.search||"";function closeDropdowns(e){let n=globalNav.querySelectorAll(".dropdown.open");dropdownItems.forEach(function(t){let o=t.querySelector(".dropdown");!n||t.contains(e.target)&&27!==e.keyCode||o.classList.remove("open")})}function gtmSendReport(e,n,t){let o={eventCategory:"ecommerce",eventAction:"componentClick",brand:e,dimension23:"global-nav",list:pageUri,pageZone:"header",variant:"nav-link"};"global-nav-link"===t&&(o.eventLabel=n.href),gtm.reportNow(o)}function updateElementTargetUrlsIfQueryStrings(e){if(searchString){const n=new URLSearchParams(searchString);let t=e.href;if(t.includes("?")){const o=t.split("?"),i=new URLSearchParams(o[1]);for(let e of n.entries())i.set(e[0],e[1]);t=`${o[0]}?${i.toString()}`,e.href=t}else e.href=`${t}?${n.toString()}`}}function init(e){const n=e.querySelectorAll(".to-landing-page");window.addEventListener("auth:init",()=>{signInButton.addEventListener("click",function(e){e.preventDefault(),auth.showEmbeddedLoginFlow("top navigation")}),signOutButton.addEventListener("click",function(e){e.preventDefault(),gtmSendReport("Sign Out",e.target,"user-info-link"),auth.logout()}),auth.isAuthenticated()&&e.classList.add("signed-in"),auth.isSubscriber()&&e.classList.add("subscribed"),e.querySelectorAll(".user-link").forEach(e=>{e.classList.add("active")}),subscriptionPromoLinks.forEach(e=>{updateElementTargetUrlsIfQueryStrings(e)}),appendLandingPageParams(n)})}dropdownItems.forEach(function(e){e.addEventListener("click",function(){e.querySelector(".dropdown").classList.toggle("open")})}),body.addEventListener("click",closeDropdowns),document.addEventListener("keydown",closeDropdowns),globalNav.addEventListener("click",function(e){let n=e.target;n.classList.contains("global-nav-track")&>mSendReport(n.text,n,"global-nav-link")}),module.exports=init;
}, {"1":1,"3":3,"12":12,"124":124,"136":136}];
window.modules["aaa-module-mounting.legacy"] = [function(require,module,exports){"use strict";const _pickBy=require(221),_each=require(408),Fingerprint2=require(407),DS=require(406),Eventify=require(246);function registerGlobals(){window.DS=DS,window.Eventify=Eventify,window.Fingerprint2=Fingerprint2,DS.value("Eventify",Eventify),DS.value("Fingerprint2",Fingerprint2),DS.value("$document",window.document),DS.value("$window",window)}function mountDollarSliceComponents(){DS.service("components",["$document","$module",function(e,n){var o=_pickBy(n.definitions,e=>e.providerStrategy===n.providers.controller),r=Object.keys(o);function t(e){return o=>{try{n.get(e,o)}catch(e){logMountError(o,e)}}}_each(r,n=>{var o=e.querySelectorAll('[data-uri*="/_components/'+n+'/"]'),r=e.querySelectorAll('[data-uri$="/_components/'+n+'"]');_each(o,t(n)),_each(r,t(n))}),this.components=r}]),DS.get("components")}function logMountError(e,n){const o=e.outerHTML.slice(0,e.outerHTML.indexOf(e.innerHTML));console.error("Error attaching controller to "+o,n)}registerGlobals(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{mountDollarSliceComponents()}):mountDollarSliceComponents();
}, {"221":221,"246":246,"406":406,"407":407,"408":408}];
window.modules["ads.legacy"] = [function(require,module,exports){"use strict";const _map=require(118),_forEach=require(107),_isString=require(268),_intersectionWith=require(409),_isEqual=require(274),_each=require(408),_debounce=require(182),_sortBy=require(205),page=require(124),visit=require(114);DS.service("adService",["Eventify","$cid","$document","$window",function(e,t,a,i){var o,n,s,r,d,c,u,l,g={},p=this,h=[],f=visit.getQueryParamsObject(["utm_campaign"]),m=document.querySelector('script[data-type="ad-a9"]'),b=[],w=!1,v=[],y=document.querySelector('script[data-name="ad-doubleverify"]');document.querySelector('script[data-name="concert-ads"]')||(i.NYM={},i.NYM.analytics={},i.NYM.analytics.adStartTime=i.performance.now(),i.googletag=i.googletag||{},i.googletag.cmd=i.googletag.cmd||[],u=i.googletag,(m||y)&&(i.googletag.cmd=i.googletag.cmd||[],i.googletag.cmd.push(function(){i.googletag.pubads().disableInitialLoad()})),m&&(l=i.setInterval(function(){void 0!==window.apstag&&void 0!==window.apstag.timeout&&(i.clearInterval(l),window.apstag.cleared=!0,l=null)},10),setTimeout(function(){l&&(i.clearInterval(l),i.googletag.pubads().refresh(),window.apstag||console.log("MESSAGE: Timeout for A9 load exceeded, aborting"))},500)),y&&(b.push(new Promise(function(e){w?e():v.push(e)})),c=i.setTimeout(T,2500)),o=function(e){var t,a,o=e.data,n=[];return o.loaded?e:(o.loaded=!0,t=null,(t=o.sizes?u.defineSlot(o.name,o.sizes,o.id).addService(u.pubads()):u.defineOutOfPageSlot(o.name,o.id).addService(u.pubads())).setTargeting("adid",o.id),f.hasOwnProperty("utm_campaign")&&t.setTargeting("utmcamp",f.utm_campaign),a=p.getAdCount(o.label),t.setTargeting("label",o.label+"_"+o.site+"-"+a),u.display(o.id),u.pubads().addEventListener("slotOnload",function(){i.NYM.analytics.firstAdLoadTime||(i.NYM.analytics.firstAdLoadTime=i.performance.now(),i.NYM.analytics.firstAdLoadLabel=e.data.label)}),n=_(o),Promise.all(b).then(function(){n?window.apstag&&window.apstag.cleared?window.apstag.fetchBids({slots:[n],timeout:window.apstag.timeout},function(){u.cmd.push(function(){window.apstag.setDisplayBids(),u.pubads().refresh([t],{changeCorrelator:!1})})}):y&&u.pubads().refresh([t],{changeCorrelator:!1}):u.pubads().refresh([t],{changeCorrelator:!1})}),e.slot=t,e)},n=function(e){var a,i,o,n=t(),s=e.getAttribute("data-name"),r=e.getAttribute("data-sizes"),d=e.getAttribute("data-label"),c=e.getAttribute("data-site");n=e.id,r&&r.length?(r=r.split(","),a=[],_map(r,function(e){e=e.split("x"),i=parseInt(e[0]),o=parseInt(e[1]),a.push([i,o])})):(e.classList.add("oop"),a=!1),this.data={id:n,name:s,sizes:a,loaded:!1,label:d,site:c},g[n]=this},r=function(e){u.cmd.push(function(){var t=o(e);g[e.data.id]=t})},s=function(e){var t=[];e.slot?(t=_(e))&&window.apstag&&window.apstag.cleared&&window.apstag.fetchBids({slots:[t],timeout:window.apstag.timeout},function(){u.cmd.push(function(){window.apstag.setDisplayBids(),u.pubads().refresh([e.slot],{changeCorrelator:!1})})}):e&&r(e)},u.cmd.push(function(){var e,t,o,n=page.getMeta("article:tag"),s=page.getMeta("author"),r=i.location.href,d=(e=a.head.querySelector(".head-gtm"),t=a.body.querySelector(".gtm"),e&&"top"===e.getAttribute("data-gtm")?"gtmtop":t&&"bottom"===t.getAttribute("data-gtm")?"gtmbottom":"");o=[],_forEach([n,s,d],function(e){_forEach(e.split(","),function(e){(e=e.trim().toLowerCase().replace(/\s/g,"-").replace(/\'|\’/g,"")).length&&o.push(e)})}),u.pubads().setTargeting("kw",o),u.pubads().setTargeting("entry_group",o),r=r.slice(r.lastIndexOf("/")+1),u.pubads().setTargeting("pn",r),u.companionAds().setRefreshUnfilledSlots(!0),u.pubads().enableAsyncRendering(),u.enableServices()}),this.load=r,this.create=function(e){return new n(e)},this.refresh=function(e){var t;_isString(e)?(t=this.getById(e),s(t)):s(e)},this.remove=function(e){var t=e.data.id;a.getElementById(t).innerHTML=""},this.getAdCount=function(e){var t,a=0,i=Object.keys(g);return _each(i,function(i){(t=g[i]).data.loaded&&t.data.label===e&&a++}),a},this.getById=function(e){return g[e]},d=_debounce(function(){var e={TopLeaderboard:1,RightColTopMPU:2,outOfPage:99,"homepageTakeover/TopLeaderboard":1},t=_sortBy(h,function(t){return e[t.data.label]||10});_forEach(t,function(e){return e.data.sizes?r(e):i.setTimeout(function(){r(e)},2e3)}),y&&window.PQ.cmd.push(()=>{try{window.PQ.loadSignals(["ids","bsc","vlp"],T)}catch(e){T(),console.error(`There has been an error loading Double Verify signals: ${e}`)}}),h=[]},10),this.addToPageLoadQueue=function(e){h.push(e),d()});function _(e){var t,a=e.sizes;return a=_intersectionWith(a,[[970,250],[970,90],[728,90],[300,600],[300,250],[320,100],[320,50]],_isEqual),e.sizes&&e.sizes.length&&(t={slotID:e.id,sizes:a,slotName:e.label}),t}function T(){i.clearTimeout(c),w=!0,_forEach(v,function(e){e()})}}]);
}, {"107":107,"114":114,"118":118,"124":124,"182":182,"205":205,"268":268,"274":274,"408":408,"409":409}];
window.modules["cid.legacy"] = [function(require,module,exports){"use strict";DS.service("$cid",function(){var r=Math.floor(100*Math.random());return function(){return"cid-"+ ++r}});
}, {}];
window.modules["client.legacy"] = [function(require,module,exports){"use strict";require("cid.legacy"),require("ads.legacy"),require("facebook.legacy"),require("aaa-module-mounting.legacy");
}, {"cid.legacy":"cid.legacy","aaa-module-mounting.legacy":"aaa-module-mounting.legacy","ads.legacy":"ads.legacy","facebook.legacy":"facebook.legacy"}];
window.modules["facebook.legacy"] = [function(require,module,exports){"use strict";DS.service("facebook",[function(){this.fb=function(i){window.FB&&window.FB[i].apply(this,Array.prototype.slice.call(arguments,1))}}]);
}, {}];
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o typeof key === 'string' && key.match(/\.legacy$/)).forEach(key => window.require(key));
}
function tryToMount(fn, el, name) {
try {
fn(el); // init the controller
} catch (e) {
const elementTag = el.outerHTML.slice(0, el.outerHTML.indexOf(el.innerHTML));
console.error(`Error initializing controller for "${name}" on "${elementTag}"`, e);
}
}
/**
* mount client.js component controllers
*/
function mountComponentModules() {
Object.keys(window.modules).filter(key => typeof key === 'string' && key.match(/\.client$/)).forEach(key => {
let controllerFn = window.require(key);
if (typeof controllerFn === 'function') {
const name = key.replace('.client', ''),
instancesSelector = `[data-uri*="_components/${name}/"]`,
defaultSelector = `[data-uri$="_components${name}"]`,
instances = document.querySelectorAll(instancesSelector),
defaults = document.querySelectorAll(defaultSelector);
for (let el of instances) {
tryToMount(controllerFn, el, name);
}
for (let el of defaults) {
tryToMount(controllerFn, el, name);
}
}
});
}
// Make sure that a `window.process.env.NODE_ENV` is available in the client for any dependencies,
// services, or components that could require it
// note: the `` value is swapped for the actual environment variable in /lib/cmd/compile/scripts.js
window.process = window.process || {};
window.process.env = window.process.env || {};
if (!window.process.env.NODE_ENV) {
window.process.env.NODE_ENV = '';
}
// note: legacy controllers that require legacy services (e.g. dollar-slice) must
// wait for DOMContentLoaded to initialize themselves, as the files themselves must be mounted first
mountLegacyServices();
mountComponentModules();
// ]]