#eventtarget
Explore tagged Tumblr posts
sistazai · 2 years ago
Photo
Tumblr media
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
vianinja · 5 years ago
Link
Tumblr media
0 notes
javascriptw3schools · 4 years ago
Photo
Tumblr media
Node and the Struggles of Being an EventTarget: https://t.co/wUyHCOY8JX
0 notes
webpacknews · 4 years ago
Photo
Tumblr media
Node and the Struggles of Being an EventTarget: https://t.co/wUyHCOY8JX
0 notes
vuejs2 · 4 years ago
Photo
Tumblr media
Node and the Struggles of Being an EventTarget: https://t.co/wUyHCOY8JX
0 notes
t-baba · 5 years ago
Photo
Tumblr media
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
Tumblr media
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
Tumblr media
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
prevajconsultants · 5 years ago
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
black7375 · 5 years ago
Text
타입스크립트 쓰면서 가장 원하는 것.
최소한 C++ auto 키워드급의 타입추론이 있으면.. 하스켈처럼은 안바란다..
동적 언어(Javascript) 기반이라 쉽지 않다는 것은 알지만.. noImplicitAny를 쓰기에는 리스크가 너무 크고, any라고 정의하면 자동완성이나 타입추론이 이상하게 된다.
이벤트나 useReducer같은 것을 이용할 때
e: React.FormEvent action: EventTarget & HTMLInputElement
위처럼 매번 타입을 적어야되는 것은 너무~~ 불편.
0 notes
bellbind · 7 years ago
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
tak4hir0 · 5 years ago
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
macronimous · 5 years ago
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
javascriptw3schools · 4 years ago
Photo
Tumblr media
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
webpacknews · 4 years ago
Photo
Tumblr media
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
dothtml5 · 8 years ago
Link
電子書籍:UIデザイナーのためのSketch入門&実践ガイド (Kindle版)
モバイルアプリにおけるメニューのベストポジションを考えてみよう (フェレット)
ロングスクロールのベストプラクティス (UX MILK)
CSV⇔JSONに変換してくれるファイルコンバータ「sqlify」 (かちびと)
Emotion APIとは (@IT)
Mojik v0.3.0 (terkel)
Vue.js: TodoMVCをつくる (05) 項目のテキストを再編集できるようにする (Fumio Nonaka)
EventTargetの継承可能化によるEventEmitterの代替 (blog jxck io)
そういえばa要素ってなんでaなの? (NoxGit | Qiita)
ワンランク上に!ウェブページのレイアウトを美調整するスタイルがまとめられたスタイルシート「fractures」 (コリス)
CSS3で創るボタンコレクション「10 Awesome CSS Button Libraries & Collections」 (DesignDevelop)
SVGで始めるマイクロインタラクション入門 (ICS MEDIA)
0 notes
suzanneshannon · 5 years ago
Text
TypeScript, Minus TypeScript
Unless you’ve been hiding under a rock the last several years (and let’s face it, hiding under a rock sometimes feels like the right thing to do), you’ve probably heard of and likely used TypeScript. TypeScript is a syntactical superset of JavaScript that adds — as its name suggests — typing to the web’s favorite scripting language.
TypeScript is incredibly powerful, but is often difficult to read for beginners and carries the overhead of needing a compilation step before it can run in a browser due to the extra syntax that isn’t valid JavaScript. For many projects this isn’t a problem, but for others this might get in the way of getting work done. Fortunately the TypeScript team has enabled a way to type check vanilla JavaScript using JSDoc.
Setting up a new project
To get TypeScript up and running in a new project, you’ll need NodeJS and npm. Let’s start by creating a new project and running npm init. For the purposes of this article, we are going to be using VShttps://code.visualstudio.comCode as our code editor. Once everything is set up, we’ll need to install TypeScript:
npm i -D typescript
Once that install is done, we need to tell TypeScript what to do with our code, so let’s create a new file called tsconfig.json and add this:
{   "compilerOptions": {     "target": "esnext",     "module": "esnext",     "moduleResolution": "node",     "lib": ["es2017", "dom"],     "allowJs": true,     "checkJs": true,     "noEmit": true,     "strict": false,     "noImplicitThis": true,     "alwaysStrict": true,     "esModuleInterop": true   },   "include": [ "script", "test" ],   "exclude": [ "node_modules" ] }
For our purposes, the important lines of this config file are the allowJs and checkJs options, which are both set to true. These tell TypeScript that we want it to evaluate our JavaScript code. We’ve also told TypeScript to check all files inside of a /script directory, so let’s create that and a new file in it called index.js.
A simple example
Inside our newly-created JavaScript file, let’s make a simple addition function that takes two parameters and adds them together:
function add(x, y) {   return x + y; }
Fairly simple, right? add(4, 2) will return 6, but because JavaScript is dynamically-typed you could also call add with a string and a number and get some potentially unexpected results:
add('4', 2); // returns '42'
That’s less than ideal. Fortunately, we can add some JSDoc annotations to our function to tell users how we expect it to work:
/**  * Add two numbers together  * @param {number} x  * @param {number} y  * @return {number}  */ function add(x, y) {   return x + y; }
We’ve changed nothing about our code; we’ve simply added a comment to tell users how the function is meant to be used and what value should be expected to return. We’ve done this by utilizing JSDoc’s @param and @return annotations with types set in curly braces ({}).
Trying to run our incorrect snippet from before throws an error in VS Code:
Tumblr media
TypeScript evaluates that a call to add is incorrect if one of the arguments is a string.
In the example above, TypeScript is reading our comment and checking it for us. In actual TypeScript, our function now is equivalent of writing:
/**  * Add two numbers together  */ function add(x: number, y: number): number {   return x + y; }
Just like we used the number type, we have access to dozens of built-in types with JSDoc, including string, object, Array as well as plenty of others, like HTMLElement, MutationRecord and more.
One added benefit of using JSDoc annotations over TypeScript’s proprietary syntax is that it provides developers an opportunity to provide additional metadata around arguments or type definitions by providing those inline (hopefully encouraging positive habits of self-documenting our code).
We can also tell TypeScript that instances of certain objects might have expectations. A WeakMap, for instance, is a built-in JavaScript object that creates a mapping between any object and any other piece of data. This second piece of data can be anything by default, but if we want our WeakMap instance to only take a string as the value, we can tell TypeScript what we want:
/** @type {WeakMap<object, string} */ const metadata = new WeakMap(); 
 const object = {}; const otherObject = {}; 
 metadata.set(object, 42); metadata.set(otherObject, 'Hello world');
This throws an error when we try to set our data to 42 because it is not a string.
Tumblr media
Defining our own types
Just like TypeScript, JSDoc allows us to define  and work with our own types. Let’s create a new type called Person that has name, age and hobby properties. Here’s how that looks in TypeScript:
interface Person {   name: string;   age: number;   hobby?: string; }
In JSDoc, our type would be the following:
/**  * @typedef Person  * @property {string} name - The person's name  * @property {number} age - The person's age  * @property {string} [hobby] - An optional hobby  */
We can use the @typedef tag to define our type’s name. Let’s define an interface called Person with required  name (a string)) and age (a number) properties, plus a third, optional property called hobby (a string). To define these properties, we use @property (or the shorthand @prop key) inside our comment.
When we choose to apply the Person type to a new object using the @type comment, we get type checking and autocomplete when writing our code. Not only that, we’ll also be told when our object doesn’t adhere to the contract we’ve defined in our file:
Tumblr media
Now, completing the object will clear the error:
Tumblr media
Our object now adheres to the Person interface defined above
Sometimes, however, we don’t want a full-fledged object for a type. For example, we might want to provide a limited set of possible options. In this case, we can take advantage of something called a union type:
/**  * @typedef {'cat'|'dog'|'fish'} Pet  */ 
 /**  * @typedef Person  * @property {string} name - The person's name  * @property {number} age - The person's age  * @property {string} [hobby] - An optional hobby  * @property {Pet} [pet] - The person's pet  */
In this example, we have defined a union type called Pet that can be any of the possible options of 'cat', 'dog' or 'fish'. Any other animals in our area are not allowed as pets, so if caleb above tried to adopt a 'kangaroo' into his household, we would get an error:
/** @type {Person} */ const caleb = { name: 'Caleb Williams', age: 33, hobby: 'Running', pet: 'kangaroo' };
Tumblr media
This same technique can be utilized to mix various types in a function:
/**  * @typedef {'lizard'|'bird'|'spider'} ExoticPet  */ 
 /**  * @typedef Person  * @property {string} name - The person's name  * @property {number} age - The person's age  * @property {string} [hobby] - An optional hobby  * @property {Pet|ExoticPet} [pet] - The person's pet  */
Now our person type can have either a Pet or an ExoticPet.
Working with generics
There could be times when we don’t want hard and fast types, but a little more flexibility while still writing consistent, strongly-typed code. Enter generic types. The classic example of a generic function is the identity function, which takes an argument and returns it back to the user. In TypeScript, that looks like this:
function identity<T>(target: T): T {   return target; }
Here, we are defining a new generic type (T) and telling the computer and our users that the function will return a value that shares a type with whatever the argument target is. This way, we can still pass in a number or a string or an HTMLElement and have the assurance that the returned value is also of that same type.
The same thing is possible using the JSDoc notation using the @template annotation:
/**  * @template T  * @param {T} target  * @return {T}  */ function identity(target) {   return x; }
Generics are a complex topic, but for more detailed documentation on how to utilize them in JSDoc, including examples, you can read the Google Closure Compiler page on the topic.
Type casting
While strong typing is often very helpful, you may find that TypeScript’s built-in expectations don’t quite work for your use case. In that sort of instance, we might need to cast an object to a new type. One instance of when this might be necessary is when working with event listeners.
In TypeScript, all event listeners take a function as a callback where the first argument is an object of type Event, which has a property, target, that is an EventTarget. This is the correct type per the DOM standard, but oftentimes the bit of information we want out of the event’s target doesn’t exist on EventTarget — such as the value property that exists on HTMLInputElement.prototype. That makes the following code invalid:
document.querySelector('input').addEventListener(event => {   console.log(event.target.value); };
TypeScript will complain that the property value doesn’t exist on EventTarget even though we, as developers, know fully well that an <input> does have a value.
Tumblr media
In order for us to tell TypeScript that we know event.target will be an HTMLInputElement, we must cast the object’s type:
document.getElementById('input').addEventListener('input', event => {   console.log(/** @type {HTMLInputElement} */(event.target).value); });
Wrapping event.target in parenthesis will set it apart from the call to value. Adding the type before the parenthesis will tell TypeScript we mean that the event.target is something different than what it ordinarily expects.
Tumblr media
And if a particular object is being problematic, we can always tell TypeScript an object is @type {any} to ignore error messages, although this is generally considered bad practice depsite being useful in a pinch.
Wrapping up
TypeScript is an incredibly powerful tool that many developers are using to streamline their workflow around consistent code standards. While most applications will utilize the built-in compiler, some projects might decide that the extra syntax that TypeScript provides gets in the way. Or perhaps they just feel more comfortable sticking to standards rather than being tied to an expanded syntax. In those cases, developers can still get the benefits of utilizing TypeScript’s type system even while writing vanilla JavaScript.
The post TypeScript, Minus TypeScript appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter.
TypeScript, Minus TypeScript published first on https://deskbysnafu.tumblr.com/
0 notes