#eventtarget
Explore tagged Tumblr posts
Photo
Kicked off 2023 arts and culture life in Naarm at The opening night of @7methods. This play!! The playwright, Jasmine Lee-Jones is a force (to quote a friend). Woooo … incredible. Loved it. So many conversations to be had with this one … wooo! Bring your beloveds. There’s free food and entertainment after, so you can lounge and talk. . . I’m extremely honoured to have worked on / adapted the Community Engagement Strategy for Naarm audiences. I tell you, this production’s community engagement game is STRONG! And that’s because so many incredible Black women have put in the work to design a strategy that engages community from Sydney, Brisbane/Meanjin and now Melbourne/Naarm. I’m absolutely humbled to have added a little bit of spice to the incredible mix. Of course, strategy needs execution. A massive shout out to @amarxchi_ and her team who executed the Naarm community engagement strategy via @malthousetheatre 👏🏾👏🏾. The season is sold out! But there’s NOTLAF tix available for folks on the receiving end of systemic f*^ks^*%. Need NOTLAF? Please see my stories for deets. Or visit https://www.malthousetheatre.com.au/tickets/malthouse-theatre/seven-methods-of-killing-kylie-jenner/#eventTarget Even if you don’t have a ticket, Vyb Nights are free for all to attend. Vyb Nights 😍 Free food, drinks and entertainment. You heard. Bring a friend or two. It’s the perfect way to wrap up a night of thought-provoking theater. Last night was so much fun with DJ from @on3.studio, my fav @msniasha singing up a storm and @junglecityprojects #ChubbyDice setting the dance floor on fire. You know we like a good party to balance out the deep conversations. Next Vyb on Saturday night features DJ, poetry and comedy. But now I’m just telling you things you probably already knew. 😂 But maybe you need to go and experience. Co-produced by @malthousetheatre, @greendoortheatreco and @darlinghursttheatreco Co-directed by @z.okenyo and @sharileesebbens Produced by @leilaadelaideenright Have the best time at the theatre, my loves. Me and @sammyylou had a blast. We’re still talking about the play - @chikathat and #lolanthe are incredible 💐💐 Image 1 📸: @tenikomo https://www.instagram.com/p/Cnn6Jrvh3Zw/?igshid=NGJjMDIxMWI=
0 notes
Text
How to propagate event? InvalidStateError: Failed to execute 'dispatchEvent' on 'EventTarget': The event is already being dispatched
I'm trying to propagate an event from my window.document to an iframe within this document.
When catching the event in the window.document I try the following:
event.preventDefault()(@dispatchTo()).dispatchEvent(event)# @dispatchTo() returns the reference of `document.querySelector('iframe').contentDocument`
But I get InvalidStateError: Failed to execute 'dispatchEvent' on 'EventTarget': The event is already being dispatched.
I tried preventDefault and stopPropagation but none would work. It seems that the event is being dispatched while I try to dispatch it to the iframe document and it fails.
How can I propagate an event to my iframe while catching it from the window.document?
I do have another eventListener on the iframe for that event, but it doesn't get triggered.
I use React (which has a virtual DOM, it may interfere, it may not, just saying).
I found part-of-a-solution there: https://stackoverflow.com/a/20541207/2391795
And now I'm able to dispatch events from the document to the iframe using this code:
eventClone = new event.constructor(event.type, event)(@dispatchTo()).dispatchEvent(eventClone)
But since I'm using React, the cloned event isn't equal to the initial event, because React has a kind-of wrapper for events. So I loose many properties, like the which and isTrusted, which become false once cloned.
Is there any way to properly clone a React event?
https://codehunter.cc/a/reactjs/how-to-propagate-event-invalidstateerror-failed-to-execute-dispatchevent-on-eventtarget-the-event-is-already-being-dispatched
0 notes
Link
0 notes
Photo
Node and the Struggles of Being an EventTarget: https://t.co/wUyHCOY8JX
0 notes
Photo
Node and the Struggles of Being an EventTarget: https://t.co/wUyHCOY8JX
0 notes
Photo
Node and the Struggles of Being an EventTarget: https://t.co/wUyHCOY8JX
0 notes
Photo
You say JavaScript, I say JS.. let's call the whole thing off?
#495 — July 3, 2020
Unsubscribe | Read on the Web
👴🏻 Just because I know you're not all as ancient as me, the subject line is a reference to an old Gershwin song 🎵😄
JS Weekly
JavaScript's Creator Recommends We Call JavaScript 'JS' — In response to a lively Twitter thread this week posing the question “If you were given the chance to rename JavaScript, what would you call it?” Brendan Eich wisely suggested, nay declared, we go with JS. While there’s an aspect of fun around this whole debate, it seems a sensible idea given JS has no relation to Java at all, although it might take us a while to rebrand ;-)
Twitter
A Brief Status Update on Vue 3.0 — The 18th beta of Vue 3.0 is out. Amongst other things, they’re targeting mid July for the first release candidate, then early August for the final Vue 3.0 release. You’re encouraged to start using it already though.
Evan You
Locate Front-End Issues Like JavaScript or Network Errors Instantly — Get proactively alerted on any client-side issues such as JavaScript and network errors, optimize the load time of your front-end resources, and detect any UI issues that affect critical user journeys. Try it free with Datadog Synthetics.
Datadog sponsor
▶ What’s New in V8 and JavaScript — A 20-minute talk from this week’s web.dev LIVE event that Google put on. The speakers cover a variety of new features and improvements to JavaScript generally as well as in V8 and Chrome.
Shu-yu Guo and Leszek Swirski (Google)
Announcing TypeScript 4.0 Beta — Last week we said the TS 4 beta was “due any moment” and last thing on a Friday was clearly the time to shine 😂 4.0 has no substantial breaking changes but there are lots of bits and pieces to play with including variadic tuple types, short-circuiting assignment operators, and editor improvements.
Daniel Rosenwasser (Microsoft)
V8 Release V8.4 — The next release of V8 (due to come out in coordinate with Chrome 84) boasts improved startup time, support for weak references and finalizers (worth seeing the code examples for these advanced features), and private methods and accessors.
Camillo Bruni
⚡️ Quick bytes:
Node 14.5 is out and includes a new experimental DOM-esque EventTarget API.
The JS2014 code golfing competition is open until July 15. You have to create something amazing in 1024 bytes (or fewer) of JavaScript.
Take care to not use the Internet Archive as a CDN for your JavaScript assets – obvious, perhaps, but a major British bank seems to have done just that 😄
💻 Jobs
JavaScript Developer at X-Team (Remote) — Join the most energizing community for developers and work on projects for Riot Games, FOX, Sony, Coinbase, and more.
X-Team
Find a Job Through Vettery — Use Vettery to connect with growing tech teams at startups and Fortune 500 companies.
Vettery
📚 Tutorials, Opinions and Stories
Understanding Template Literals — I really like Tania’s tutorials as they are both straightforward and thorough. Template literals are a piece of syntax (introduced in ES6/ES2015) worth understanding if you don’t use them yet.
Tania Rascia
The !! Operator and a Misunderstanding of How JS Handles Truthy / Falsy Values — Ben Nadel has noticed developers using the double-bang (!!) operator far more often in their JavaScript code than they have to. As such, he provides a series of unnecessary examples followed by cleaner, more intuitive examples.
Ben Nadel
CascadiaJS 2020 - An Online Conf for Web Devs That’s Actually Fun 🎉 — More than just a live stream, network and socialize with 1000+ fellow JS devs. Save 20% off with promo code JSWEEKLY.
CascadiaJS sponsor
▶ Low Code for the Node.js Developer with Node-RED — The project lead of Node-RED, a visual, Node-based ‘low code’ programming tool, talks about the concepts of ‘low code’ in the Node space and how Node-RED works.
Nick O Leary (IBM)
▶ The Bits And Bytes of Binary — Do you need to know the ins and outs of messing with binary in order to build a web app? No. But binary nonetheless runs the show at the low level, including in many algorithms, and this series from Low Level JavaScript covers the basics well.
Low Level JavaScript
Tips for Golfing in JavaScript — If you're thinking of entering JS1024 or otherwise want to take pleasure in crushing your JavaScript into as few bytes as possible, this collection of tips and tricks is for you. (Golfing is the art of representing an idea in as little code as possible.)
Stack Exchange
Continuous Deployment of Gatsby Apps to Heroku
CircleCI sponsor
An In-Depth Beginner's Guide to Testing React Apps — A lot of posts will say ‘in-depth’ and be 500 words long – this isn’t one of those! If you’re a beginner to testing, there’s a lot to chew on here but it stays accessible throughout.
Johannes Kettmann
Exploring the Web Speech API — One of those APIs I keep forgetting exists but with which you can do some pretty cool stuff.
James at De Voorhoede
TodoMVC Implemented Using a Game Architecture: ECS — Can you build more traditional GUIs with the Entity Component System as popular in game development? An interesting idea.
Andy Bulka
Getting Started with the Vue 3 Composition API
Joel Parks
🔧 Code & Tools
Vest: Effortless Validations Inspired by Testing Frameworks — If you’re used to unit testing, the syntax used here will be familiar.
Evyatar
React Hook Form 6.0: Simple, Extensible React Form Validation — Now with better TypeScript support, a smaller package size, and numerous refinements and improvements, RHF is certainly worth a look if you’re building or refactoring forms. GitHub repo.
Blue Bill
Stream Chat API & JavaScript SDK for Custom Chat Apps — Build real-time chat in less time. Rapidly ship in-app messaging with our highly reliable chat infrastructure.
Stream sponsor
Hyperapp: (Another) Tiny Framework for Building Web Interfaces — Claims to be 2x faster than React and comes in at less than 2KB.
Jorge Bucaran
Textures.js: SVG Textures for Data Visualization — Built on top of d3.js, this lets you bring together patterns and colors in an elegant and, dare we say, old school manner.
Riccardo Scalco
emoji-picker-element: A Lightweight Emoji Picker for the Modern Web — See a live demo here. Some cool performance advantages for this: It’s a web component and it’s built on Svelte and IndexedDB.
Nolan Lawson
🎨 Creative Corner
24a2: An Ultra-Minimalist Dot Matrix-Based Game Engine — What makes this different is that it has a limited set of features so you can build a game in a few hours. Here’s an example.
James Routley
PHONK: A Creative Scripting Toolbox for Android Devices — If you’ve got any old Android devices sat around, this could be a way to have some fun with them. It’s based around JavaScript.
Victor Diaz
parallax-effect: Parallax Effect in JavaScript using Face Tracking — A lot of designers seem to love parallax effects, whereas a lot of us end users aren’t so keen. But if you’re going to do it, do it in an over the top creative way like this 😂
munrocket
by via JavaScript Weekly https://ift.tt/2ZAv3Ht
0 notes
Text
RT @codebytere: 🥳 @nodejs v14.5.0 has been released! 🥳 Of note: - V8 has been updated to v8.3 (h/t @mmarkini @targos89)! - New experimental EventTarget API (h/t @jasnell!) More here (soon) 👇🏻 https://t.co/TeJ157wgYf
🥳 @nodejs v14.5.0 has been released! 🥳 Of note: - V8 has been updated to v8.3 (h/t @mmarkini @targos89)! - New experimental EventTarget API (h/t @jasnell!) More here (soon) 👇🏻 https://t.co/TeJ157wgYf
— shelley (@codebytere) June 30, 2020
nodejs
0 notes
Text
Typescript types for React checkbox events and handlers?
I'm building something like this React example in Typescript. The goal is to have a parent that has a state, and it creates several stateless child components that pass their clicks back to the parent.
Since the example is in Javascript I have no idea what the types of the input box events and the onChange handlers are...? I've tried several options like React.MouseEvent<HTMLInputElement>, but that's just guesswork...
Parent component create imageRows and pass the handler:
render() { <div> <ImageRow key={el.url} onChange={this.onChange}/> </div> } // what should the type of e be? onChange(e:any){ }
And the ImageRow component
export interface ImageRowProps { genre: Array<number> url: string onChange : any // what is the type of the callback function?}export class ImageRow extends React.Component<ImageRowProps> { render() { return <div className="imagerow"> <input type="checkbox" key={index} onChange={this.props.onChange} defaultChecked={(num == 1)}/> </div>}
EDIT
The similar question only shows the event type, not the handler type. When I change the event type:
onChange(e: React.FormEvent<HTMLInputElement>){ console.log(e.target.value)}
I get this error:
Property 'value' does not exist on type 'EventTarget'.
https://codehunter.cc/a/reactjs/typescript-types-for-react-checkbox-events-and-handlers
0 notes
Text
타입스크립트 쓰면서 가장 원하는 것.
최소한 C++ auto 키워드급의 타입추론이 있으면.. 하스켈처럼은 안바란다..
동적 언어(Javascript) 기반이라 쉽지 않다는 것은 알지만.. noImplicitAny를 쓰기에는 리스크가 너무 크고, any라고 정의하면 자동완성이나 타입추론이 이상하게 된다.
이벤트나 useReducer같은 것을 이용할 때
e: React.FormEvent action: EventTarget & HTMLInputElement
위처럼 매번 타입을 적어야되는 것은 너무~~ 불편.
0 notes
Link
タブでWebサーバのreverse proxyゲートウェイの プロトタイプをもとに、 EventTargetやRequest/Responseといったモダンブラウザ標準APIで利用可能にしたものである。
さらに、公開鍵のハッシュ値と電子署名を使っ��、タブ固有のURLをreverse proxyで利用するようにしてある。 非公開鍵暗号処理ではサーバブラウザともに、ellipticを使っている。
そして、package.jsonの文字列に埋めてあるように、かんたんにherokuに設置可能にした。
内容:
proxyd.js: 汎用reverse proxyゲートウェイのnodejsサーバ(npm i && node proxyd.jsでポート3000で実行)
proxyd-browser.js: ブラウザ用のエンドポイントライブラリ(ReverseTargetをexport)
proxyd-browser.m.js: ES6モジュールなブラウザ用エンドポイントライブラリ(内容はproxyd-browser.jsと一緒)
tab-web-server-example.{html,js}: hello Worldコード例
コード例にあるように、エンドポイントのAPIはServiceWorkerの"fetch"イベント(FetchEvent)とまったく同じ構造にしている。 ユーザは、ブラウザ標準のclassであるRequestと Responseを処理するだけにしてある。
demoページ
** NOTE for Streams API
ResponseやRequestのbodyを一度に全体処理しかできないのは現行の標準APIの制限である。 Web Socket層も単純化のため1コネクション上での一括パケット送受信で実装してある。
これはWHATWG Streams APIで拡張される予定になっている。 もしRequest/ResponseともにbodyでReadableStreamが使えるようになり、 対応させるにはWeb Socket層も何らかの手段で多重化する必要があるだろう。
パケットとして、{乱数ID32バイト、タイプ1バイト、データ任意バイト}になるだろうか。 パケットタイプはHEADER(utf8), BODY(binary), CLOSE(utf8)の3種になるだろう。
(たとえ別コネクションを使っても、WebSocketにはhalf closeがないので、 Readderのclose状態に対応した 終了マーカーは必要になる。)。
2 notes
·
View notes
Link
RFC: Wire Adapters Status Summary The data service defines two categories of invariants: Fundamental and Component Integration. Imperative access for DML and non-DML operations is assumed. Using the callable's identity as the identifier of the wire adapter (the pluggable mechanism of the data service) is assumed. This RFC defines a protocol for wire adapters so new wire adapters may be authored and consumed by components without coordination of the framework. Basic example A component demonstrating consumption of the todo wire adapter and then requesting a refresh of the data stream. import { LightningElement, wire } from 'lwc'; import { getTodo, refreshTodo } from 'todo-wire-adapter'; export default class TodoViewer extends LightningElement { @api id; // Wire identifier is the imported callable getTodo @wire(getTodo, { id: '$id' }) wiredTodo; imperativeExample() { getTodo({id: 1}) .then(todo { ... }); } refreshExample() { this.showSpinner(true); // Request refresh using the value emitted from the wire. refreshTodo(this.wiredTodo) .then(() this.showSpinner(false)); } } An implementation of the todo wire adapter that uses observables for a stream of values. import { register, ValueChangedEvent } from 'wire-service'; // Imperative access. export function getTodo(config) { return getObservable(config) .map(makeReadOnlyMembrane) .toPromise(); } // Declarative access: register a wire adapter factory for @wire(getTodo). register(getTodo, function getTodoWireAdapterFactory(eventTarget) { let subscription; let config; // Invoked when config is updated. eventTarget.addListener('config', (newConfig) { // Capture config for use during subscription. config = newConfig; }); // Invoked when component connected. eventTarget.addListener('connected', () { // Subscribe to stream. subscription = getObservable(config) .map(makeReadOnlyMembrane) .map(captureWiredValueToConfig.bind(config)) .subscribe({ next: (data) wiredEventTarget.dispatchEvent(new ValueChangedEvent({ data, error: undefined })), error: (error) wiredEventTarget.dispatchEvent(new ValueChangedEvent({ data: undefined, error })) }); }) // Invoked when component disconnected. eventTarget.addListener('disconnected', () { // Release all resources. subscription.unsubscribe(); releaseConfig(config); }); }); // that // resolves when all wires are updated. export function refreshTodo(wiredValue) { return getConfig(wiredValue).map(getTodo); } Motivation The data service defines a declarative mechanism for a component to express its data requirements: the @wire decorator. Imperative access (discussed elsewhere) enables components to orchestrate control flow which is generally required for DML operations. The protocol for wire adapters is not formalized so new adapters require coordination with the framework and knowledge of the wire service implementation. Supporting refresh of values emitted by the wire service (wired values) is not possible because wire adapters can't associate the wired value and the originating wire adapter configuration. Goals of this proposal Enable non-framework developers to define new wire adapters Enable wire adapters to implement imperative refresh capabilities that operate on the wired value Maintain the easy-to-use declarative @wire decorator Maintain the ability to initiate data fetch at component creation Maintain a component's ability to orchestrate control flow, specifically for DML operations Proposal A wire adapter provisions data to a wired property or method using an Event Target. A factory function is registered for declarative @wire use by a component. // Events the wire adapter can dispatch to provision a value to the wired property or method interface ValueChangedEvent { value: any; new(value: any) : ValueChangedEvent; } // Event types the wire adapter may listen for type eventType = 'config' | 'connect' | 'disconnect'; interface ConfigListenerArgument { [key: string]: any; } type Listener = (config?: ConfigListenerArgument) void; interface WireEventTarget extends EventTarget { dispatchEvent(event: ValueChangedEvent): boolean; addEventListener(type: eventType, listener: Listener): void; removeEventListener(type: eventType, listener: Listener): void; } // Registers a wire adapter factory for an imperative accessor register(adapterId: Function|Symbol, wireAdapterFactory: (eventTarget: WireEventTarget) void): undefined; In the component's wiring lifecycle, the wire service invokes the wireAdapterFactory function to configure an instance of the wire adapter for each @wire instance (which is per component instance). eventTarget is an implementation of Event Target that supports listeners for the following events: config is delivered when the resolved configuration changes. A singular argument is provided: the resolved configuration. connect is delivered when the component is connected. disconnect is delivered when the component is disconnected. The wire service remains responsible for resolving the configuration object. eventTarget delivers a config event when the resolved configuration changes. The value of the configuration is specific to the wire adapter. The wire adapter must treat the object as immutable. The wire adapter is responsible for provisioning values by dispatching a ValueChangedEvent to the event target. ValueChangedEvent's constructor accepts a single argument: the value to provision. There is no limitation to the shape or contents of the value to provision. The event target handles property assignment or method invocation based on the target of the @wire. The wire adapter is responsible for maintaining any context it requires. For example, tracking the values it provisions and the originating resolved configuration is shown in the basic example. Imperative Imperative access to data is unchanged. The wire adapter module must export a callable. The callable's arguments should (not must) match those of the wire adapter's configuration. The return value is adapter specific; it need not be a promise. Refresh Wire adapters may optionally implement a refresh mechanism by defining an importable callable with the signature below. The function receives one argument: the wired value emitted by a @wire. type refresh: (wiredValue: any) promise<any The callable receives one argument, wiredValue, which is the value emitted from the wire adapter (the parameter to the ValueChangedEvent constructor). The callable must return a that resolves after the corresponding @wire is updated (assuming it updates). The value resolved is adapter specific. Advantages Event listening and dispatching is a well-understood pattern. EventTarget is a well-understood interface of this pattern. The wire adapter has control of the shape of value it provisions. The wire adapter has control over how it emits read-only values, enabling optimizations specific to the adapter. eventTarget unifies emitting values to wired properties or wired methods. The wire adapter need not handle this. Symmetry of using @wire and requesting a refresh creates an easy-to-use API. Caching behavior remains controlled by and private to the wire adapter. Access to the wire adapter factory (the callable registered with the wire service) remains private. It is not importable by components. Wire adapters can be registered at any time (not just at application boot). This enables fetching wire adapters only when they are required by a module. It provides a path for additional "context" (eg the host element) to be provided to the wire adapter. See Extended Proposal. Disadvantages Wire adapters may emit complex types that are challenging to use. For example, emitting observables requires significant expertise of the component author. The Angular2+ community's struggle with learning RxJS demonstrates this risk. The complexity of a wire adapter is increased from what it is today. This can be mitigated with factory functions that minimize boilerplate code. If refresh is not supported then the wire adapter code is even simpler. Other processes are required to ensure uniformity among similar adapters (eg those provided by a single vendor like Salesforce). The shape and semantics of data and error, arguments, etc should be consistent to provide an easy-to-use API. Wire adapters require registration to support the declarative @wire syntax. Adapter registration can happen after application boot by importing register from wire-service. Non-registered wire adapters could still function with @wire(getType) if the wire service uses getType for a one-time resolution. Refreshing a wired method requires capturing the wired value. This burden is considered acceptable because it's little code and wiring methods is an advanced use case. Extended Proposal There are known use cases where adapters will use DOM Events to retrieve data from the DOM hierarchy. This is not possible because wire adapters are not provided access to the host element as an EventTarget. This section proposes a solution: the EventTarget provided to the wire adapter factory bridges dispatched events to the host element. Extended basic example The component code changes slightly. import { LightningElement, wire } from 'lwc'; import { getTodo, refreshTodo } from 'todo-wire-adapter'; export default class TodoViewer extends LightningElement { @api id; @wire(getTodo, { id: '$id' }) wiredTodo; imperativeExample() { // Difference: pass this getTodo(this, {id: 1}) .then(todo { ... }); } refreshExample() { this.showSpinner(true); refreshTodo(this.wiredTodo) .then(() this.showSpinner(false)); } } This implementation of the todo wire adapter uses DOM Events to retrieve the data from a parent element. import { register, ValueChangedEvent } from 'wire-service'; // Difference: receive an eventTarget, use DOM Events to fetch the observable function getObservable(eventTarget, config) { let observable; const event = new CustomEvent('getTodo', { bubbles: true, cancelable: true, composed: true, detail: { config, callback: o { observable = o; } } }); eventTarget.dispatchEvent(event); return observable; } // Wire adapter id isn't a callable because it doesn't support imperative invocation export const getTodo = Symbol('getTodo'); register(getTodo, function getTodoWireAdapterFactory(eventTarget) { let subscription; let config; eventTarget.addListener('config', (newConfig) { config = newConfig; }); eventTarget.addListener('connected', () { // Difference: pass eventTarget subscription = getObservable(eventTarget, config) .map(makeReadOnlyMembrane) // Difference: capture eventTarget .map(captureWiredValueToEventTargetAndConfig.bind(eventTarget, config)) .subscribe({ next: (data) wiredEventTarget.dispatchEvent(new ValueChangedEvent(data)), error: (error) wiredEventTarget.dispatchEvent(new ValueChangedEvent(error)) }); }) eventTarget.addListener('disconnected', () { subscription.unsubscribe(); // Difference: release eventTarget releaseEventTargetAndConfig(config); }); }); export function refreshTodo(wiredValue) { // Difference: retrieve eventTarget and config return getEventTargetAndConfig(wiredValue).map(getTodo); } The scope of changes is minimal: the event target re-dispatches events other than ValueChangedEvent to the host element. Rejected Proposals Proposal 1: Promise-based Writing a new wire adapter should be as easy as implementing a module that exports a callback with a simple protocol: export function getFoo(config) { //` } The adapter must be a callable that expects exactly one argument. The argument provided to the adapter is the resolved configuration. Its type is object; the keys and values are type any. The result of calling the adapter must be a Promise that resolves to the data type serviced by the adapter. Advantages Wire adapter does not require registration. Caching behavior remains in control of and private to the wire adapter. API of @wire and imperative access is unchanged from a component perspective. Component can invoke the callable the same as @wire does. Promises are a well-known protocol, minimal learning curve. Disadvantages Wire adapter can't return non-promise values. No way for the wire adapter to update the data it returned in the promise. Wire adapter can return a new promise only when the configuration changes. Proposal 2: Observables-based This proposal is similar to Proposal 1 except that it uses observable instead of promises. Note: this proposal does not specify the observable protocol, that can be specified somewhere else. Writing a new wire adapter should be as easy as implementing a module that exports a callback with a well defined protocol for observables: export function getFoo(config) { // return an observable that emits `foo` } The adapter must be a callable that expects exactly one argument. The argument provided to the adapter is the resolved configuration. Its type is object; the keys and values are type any. The result of calling the adapter must be an observable. Advantages Wire adapter does not require registration. Caching behavior remains in control of and private to the wire adapter. Component can invoke the callable the same as @wire does. Component authors have access to observables, which are a powerful construct. Disadvantages Observables are not a natural fit for DML operations. Requiring component authors to be experts in observables increases the learning curve drastically. As a reference, the Angular2 community's struggle with learning RxJS. Observables are a stage 1 spec and undergoing significant churn. LWC guarantees backwards compatibility so the wire service and/or adapters take on that responsibility. Leaking subscriptions and async functional issues is a foot gun. We'd need to solve this. No clear path to give the wire adapter access to the component instance or other contextual data. Proposal 3: Thenable observable This proposal is similar to Proposal 2 except that it combines observable and thenable structures into a single object. The adapter must return a thenable that might or might not implement the observable protocol. This means that imperative calls to that adapter will return something that is compatible with the promise protocol, which is easy to use, while the @wire decorator and advanced users can rely on the observable protocol to get a stream of data. This variation of proposal 2 addresses several disadvantages by enabling usage of the standard promise protocol. This variation introduces two main problems: Combining thenable with observable is itself new and confusing. By exposing a non-standard observable protocol to the end-user, we open the door for potential problems in the future. Proposal 4: Public thenable and private observable This proposal is a combination of proposals 1 and 2: Imperative invocation returns a promise. @wire invocation returns an observable. Rationale for the imperative behavior: Users are much more familiar with promises than observables. The former is part of the language. Requiring expertise in observables increases the learning curve drastically. As a reference, look at the Angular2 community's struggle with learning RxJS. Observables are easy to create leaks and functional issues. Eg subscribe to an observable, next() handler updates component state, and then the component is destroyed. The subscription is leaked (only possible to unsubscribe with the return value from subscribe). Subsequent invocation of the next() handler will throw (or be useless) due to the component being destroyed. This is a foot gun. A promise is a better fit for DML operations which requires imperative invocation so the component manages control flow. Rationale for @wire behavior: @wire is limited to read operations; specifically, read operations that are memoizable (idempotent, side-effect free, etc). This is because using @wire transfers data loading control flow to the system. The system will provision the data to the component it on its timeframe. The invariant is that it happens after component constructor and prop setting. @wire avoids leaks and "destroyed component" errors by hooking the lifecycle of the component. This is possible because @wire runs in "privileged space" via the wiring lifecycle hook. The wire adapter: Must expose an API that returns promises for userland imperative invocation Must expose an API that returns an observable for @wire invocation Ensure consistency of data across those invocation paradigms. Maintains control of caching. The implementation of this is private to the wire adapter. Is highly recommended to use multi-cast observables and other techniques to minimize memory consumption and runtime. Is recommended to provide a cache invalidation mechanism, provided as an imperative JS API that's invocable from userland. Addressing issues from proposal 3 The API that returns an observable doesn't have to be exposed to components; instead it can be registered, maybe via wire.registerAdapter(publicPromiseBaseAPI, privateObservableBaseAPI) in the module that defines both functions, which guarantees that users will access the publicPromiseBaseAPI, and that's what they will provide as the identify of the adapter via the @wire decorator, while the internals of the @wire decorator can invoke privateObservableBaseAPI instead to obtain access to the observable. Proposal 5: callbacks This proposal differs from the primary proposal only in the ergonomics exposed to the wire adapter developer: To provision values, the wire adapter receives a function instead of an event Event Target. To observe changes to the resolved configuration and component lifecycle, the wire adapter factory returns an object with several callback functions instead of listening to events from the Event Target. register(getType, function wireAdapter(targetSetter) { return { updatedCallback: (config) { }, connectedCallback: () { }, disconnectedCallback: () { } }; }); Disadvantages Multiple patterns (function callbacks, event emitting) must be implemented in the wire adapter. A wire adapter is unable to unregister from callbacks. That is, by providing a connectedCallback function the wire adapter will always receive notification of component connected.
0 notes
Text
#NodeJS and the struggles of being an EventTarget https://t.co/A2cfDhHbvm #JavaScript https://t.co/B5ZsxLOHsF
#NodeJS and the struggles of being an EventTarget https://t.co/A2cfDhHbvm #JavaScript pic.twitter.com/B5ZsxLOHsF
— Macronimous.com (@macronimous) August 16, 2020
from Twitter https://twitter.com/macronimous August 17, 2020 at 12:22AM via IFTTT
0 notes
Photo
RT @codebytere: 🥳 @nodejs v14.5.0 has been released! 🥳 Of note: - V8 has been updated to v8.3 (h/t @mmarkini @targos89)! - New experimental EventTarget API (h/t @jasnell!) More here (soon) 👇🏻 https://t.co/TeJ157wgYf
0 notes
Photo
RT @codebytere: 🥳 @nodejs v14.5.0 has been released! 🥳 Of note: - V8 has been updated to v8.3 (h/t @mmarkini @targos89)! - New experimental EventTarget API (h/t @jasnell!) More here (soon) 👇🏻 https://t.co/TeJ157wgYf
0 notes
Link
0 notes