News for hackers. Stuff that matters.
Re:A proposal to add signals to JavaScript by mg on Sunday March 31, 2024 @02:54PM (#39886969)
When I need to signal something across my application, I use events:

    window.dispatchEvent(new Event('counterChange'));
And every part of the application that wants to react to it can subscribe via

    window.addEventListener('counterChange', () => {
        ... do something ...
    });
Anything wrong with that?
Re:A proposal to add signals to JavaScript by dakom on Sunday March 31, 2024 @04:38PM (#39887869)
It's often desirable for UI to be described in a declarative fashion, i.e. instead of where you have "do something" (set button color to red), refactoring so it becomes "is something" (button is red if state is x)

I might not be describing that well, because once you go down that road it really becomes a whole overall approach that infects the whole program (like functional reactive programming), and so it's really about how the whole flow fits together from top to bottom, and that can be very elegant.

I don't think that's the right fit for everything, i.e. in gamedev it might make more sense to just update some object's position imperatively, but for UI it tends to work pretty well.

Re:A proposal to add signals to JavaScript by _the_inflator on Sunday March 31, 2024 @03:18PM (#39887183)
Historically, this example is the reason why the Web evolved into jQuery and from there forked into the world of Angular and React mainly.

Event handling is getting messy very easily. If you want to get deeper into it, have a look at event bubbling and propagation.

Large applications need a robust event handling. This is the nowadays hidden benefit of frameworks like Angular, Vue etc.

Believe me, you don’t want to use the standard event handling API without a framework. Adding, deleting, cloning, firing, removing, fire once etc on many elements can have serious unwanted side effects.

Re:A proposal to add signals to JavaScript by beezlewax on Sunday March 31, 2024 @03:49PM (#39887444)
What kind of side effects specifically?
Re:A proposal to add signals to JavaScript by doomroot on Sunday March 31, 2024 @03:54PM (#39887490)
I believe memory leaks to start
Re:A proposal to add signals to JavaScript by falcor84 on Sunday March 31, 2024 @04:15PM (#39887639)
Are you implying that there are memory leaks in browsers' internal implementation of events? Because my take is that the problem is with "user space" scripts not cleaning up after themselves, and I don't see how that would get better by adding yet another API to be mindful of.
Re:A proposal to add signals to JavaScript by gibbitz on Sunday March 31, 2024 @05:59PM (#39888446)
I believe this would be more related to something like memoizing a DOM structure in a "Live" listener that is later removed from the DOM but not garbage collected due to the reference in the event listener. As the poster mentioned, developer error -- not a fundamental language or browser implementation flaw.
Re:A proposal to add signals to JavaScript by naasking on Tuesday April 02, 2024 @12:24AM (#39902371)
If a language or browser implementation can't reclaim this unused memory thus creating a memory leak, that arguably is a flaw. It's literally a DoS attack vector that can be exploited by the untrusted scripts that run in the browser sandbox.
Re:A proposal to add signals to JavaScript by Klonoar on Sunday March 31, 2024 @05:42PM (#39888306)
This is one of those points where you need to link to some kind of data or conclusive result actually showcasing this, because you're arguing against a pattern that's been in browser ecosystems for decades. I've done this for larger applications and haven't experienced issues.

Being charitable, the best I can imagine right now that'd cause memory leaks is someone running into the old school JS scoping issues and capturing something in handlers that they shouldn't. That's not the handler itself that's the problem, though - that's the developer.

(Yes, we could rant on and on about the poor design decisions that JS has built in, but that's been beaten to death)

Re:A proposal to add signals to JavaScript by unemployable on Sunday March 31, 2024 @06:50PM (#39888906)
Memory leaks can occur when a component adds events to an element outside of the component (such as the window) and then gets removed from the DOM without removing the event handler from the window. This is solved in native Web Components by the mount/unmount methods where you can run code to remove event listeners when the component has been unmounted.

For other event listeners, they get removed when the DOM element is removed.

The frameworks do not solve this to any greater degree. They also just make everything invisible and behind-the-scenes and hard to debug due to their declarative nature, but that is another topic.

Re:A proposal to add signals to JavaScript by pcthrowaway on Monday April 01, 2024 @01:07AM (#39891090)
Removing event listeners upon some component being removed actually sounds like a great use case for the new FinalizationRegistry API[1]

[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

Re:A proposal to add signals to JavaScript by ngc6677 on Monday April 01, 2024 @02:29AM (#39891387)
Example with web components in all frameworks https://webcomponents.dev/blog/all-the-ways-to-make-a-web-co... and an other version to experiment with https://jsbin.com/yiviragiba/8/edit?html,css,js,console,outp...
Re:A proposal to add signals to JavaScript by andrewstuart on Sunday March 31, 2024 @03:53PM (#39887481)
I use events extensively in large applications and its never been a problem. In fact they solve complexity.
Re:A proposal to add signals to JavaScript by unemployable on Sunday March 31, 2024 @06:45PM (#39888838)
>If you want to get deeper into it, have a look at event bubbling and propagation.

In this example, the event is on the Window. There is no bubbling. It is already at the top level.

>Believe me, you don’t want to use the standard event handling API without a framework. Adding, deleting, cloning, firing, removing, fire once etc on many elements can have serious unwanted side effects.

I don't know what this means. The frameworks do not have much to do with this topic.

Re:A proposal to add signals to JavaScript by pquki4 on Sunday March 31, 2024 @07:15PM (#39889110)
I think the previous comment discusses events in a general sense.

Frameworks batch changes so that updates are efficient, and in many cases figures out the "correct" order of doing things. If you do all of those yourself in a large and complex UI, very likely you are updating the DOM less efficiently than what frameworks are doing, and very likely you introduced some subtle bugs. Speaking of that from my first-hand experience.

Re:A proposal to add signals to JavaScript by zdragnar on Sunday March 31, 2024 @03:16PM (#39887161)
According to TFA, event emitters / observables cause unnecessary work when called multiple times.

The difference with signals is that the resulting value is only ever calculated when the end consumer reads the value- so you schedule render updates asynchronously from the actual writes to the signal, and whatever chain of computations the watchers perform is done just the one time during the render.

Interim values sent to the signal will get lost, so you really can't do too much interesting work in them. It's really just a fancy abstraction layer to coordinate a rendering cycle.

Re:A proposal to add signals to JavaScript by hk__2 on Sunday March 31, 2024 @03:00PM (#39887026)
> Anything wrong with that?

It has all the downsides of the pub/sub architecture highlighted in the proposal.

Re:A proposal to add signals to JavaScript by djbusby on Sunday March 31, 2024 @03:03PM (#39887047)
I've been using patterns like this for more than a decade. The thing that's hard is, down the road you could have a listener, which triggers a other event, then another event, which comes back to the first routine and now you got a listen-loop that won't quit.

And it's hard to ensure that all listener don't cause that trigger cascade.

Re:A proposal to add signals to JavaScript by eddd-ddde on Sunday March 31, 2024 @03:09PM (#39887094)
Isn't it possible to define all listeners / publishers in a declarative way which can be compiled to catch for this issues?
Re:A proposal to add signals to JavaScript by berkes on Sunday March 31, 2024 @06:21PM (#39888622)
Yes. It is. And most pub/sub or Observer architectures and design patterns have the "loop" thing solved just fine.

In fact, the GOF spend an entire paragraph on the problem of complex update semantics in "design Patterns" (1995) ch Observer p299.

So, while it is a real problem, it's one that has been solved (for at least 29 years)

Re:A proposal to add signals to JavaScript by djbusby on Sunday March 31, 2024 @07:24PM (#39889200)
Yes, I want to mention, since I was up-thread, it is solved but not all tooling or environment are setup for that.

When the app is small you likely don't need it. And then it grows and you absolutely do.

It's better, in greenfield to use framework/tooling that is ready for it.

Re:A proposal to add signals to JavaScript by berkes on Monday April 01, 2024 @09:16AM (#39893851)
Good to hear you found it solved!

> It's better, in greenfield to use framework/tooling that is ready for it.

I don't really agree. Tooling, and even more so, Frameworks, come with giant trade-offs. Some are "paint-in-a-corner" trade-offs. So I would caution against pulling in a framework just to solve potential future issues. So much so, that I think it is one of the top10 things that will cause your project or startup to fail or get into serious trouble. It's really a form of "premature optimization".

Re:A proposal to add signals to JavaScript by jbreckmckye on Sunday March 31, 2024 @08:20PM (#39889545)
In fact I solved a similar issue in my JS reactive micro library in just 500 bytes: https://github.com/jbreckmckye/trkl
Re:A proposal to add signals to JavaScript by briantakita on Sunday March 31, 2024 @09:47PM (#39890106)
I was not aware of trkl. Well done! I wrote rmemo (Reactive Memo) which solves the same problems & is a similar size. Different semantics though.

https://github.com/ctx-core/rmemo

Nanostores is also small https://github.com/nanostores/nanostores.

And if you only need reactivity in the browser (not server side), VanJS is small & includes reactive primitives. https://vanjs.org/

Re:A proposal to add signals to JavaScript by rrr_oh_man on Tuesday April 02, 2024 @01:07AM (#39902575)
That looks great! Thanks for sharing!
Re:A proposal to add signals to JavaScript by zaphar on Sunday March 31, 2024 @09:24PM (#39889970)
I like signals as primitive but in this particular case they make it roughly about as easy to create loops accidentally as events do. I don't think this problem gets better or worse with signals.
Re:A proposal to add signals to JavaScript by naasking on Tuesday April 02, 2024 @12:33AM (#39902408)
Signals are a bit better because they only propagate when computed values actually changed. This is an implicit fixed point/stopping condition that doesn't intrinsically exist with events.
Re:A proposal to add signals to JavaScript by lelanthran on Sunday March 31, 2024 @03:57PM (#39887512)
> Anything wrong with that?

Well, don't events only bubble upwards? You need to know the exact element of it is not on a lower level in the DOM tree.

Events were too messy, so I wrote a small pub/sub message queue type of thing. Anyone anywhere in the DOM can subscribe to messages based on subject regexes.

Makes things a lot easier, especially when I added web components to wrap existing elements so that publishing and subscribing is done with attributes, not js.

Re:A proposal to add signals to JavaScript by everybackdoor on Sunday March 31, 2024 @06:08PM (#39888512)
You can also fire events on pretty much any object, essentially creating a channel where the message bus queue is the vm event queue.
Re:A proposal to add signals to JavaScript by lelanthran on Monday April 01, 2024 @12:53AM (#39891032)
> You can also fire events on pretty much any object,

Only if you have a reference to the object.

The reason I made up my own message queue pub/sub is because events required a lot of complexity in acquiring the correct reference to the correct object or subtree in the DOM.

With pub/sub type message queue, any element can emit a message with subject "POST /getnetpage" and the function listening for (subscribed) POST messages emits a RESPONSE message when the response comes back. This lets a third element listen (subscribe) for a "RESPONSE FROM /getnextpage" subject message, and handle it.

None of the 3 parties in the above need to have a reference to each other, nor do they even have to know about each other, and I can inject some nice observability tools because I can just add a subscriber for specific message types, which makes debugging a breeze.

Re:A proposal to add signals to JavaScript by explaininjs on Sunday March 31, 2024 @03:10PM (#39887105)
This pattern is precisely what everyone's favorite "look, JS/electron can be high performance!" example uses. (VS Code).
Re:A proposal to add signals to JavaScript by cyanydeez on Sunday March 31, 2024 @03:03PM (#39887049)
Mostly the teardown logic and inevitable memory leaks.

A alt proposal would be some kind of auto remove listener if it goes out of context

Re:A proposal to add signals to JavaScript by explaininjs on Sunday March 31, 2024 @03:07PM (#39887074)
The new `using` feature handles RAII just fine. This proposal is entirely unnecessary given the existence of `using` and the already-existing event listeners. https://iliazeus.github.io/articles/js-explicit-resource-man...
Re:A proposal to add signals to JavaScript by lelandfe on Sunday March 31, 2024 @06:53PM (#39888925)
Quite a good link, thanks.
Re:A proposal to add signals to JavaScript by cyanydeez on Sunday March 31, 2024 @07:38PM (#39889323)
Nice, but mixing typescript into a proposed standard just confusing.
Re:A proposal to add signals to JavaScript by explaininjs on Sunday March 31, 2024 @10:46PM (#39890422)
The standard doesn't have anything to do with TypeScript, not sure where you got that from? https://github.com/tc39/proposal-explicit-resource-managemen...
Re:A proposal to add signals to JavaScript by cyanydeez on Monday April 01, 2024 @07:53PM (#39900823)
Im referring to the link. Trying to demonstrate a proposed feature usingvtypescript.
Re:A proposal to add signals to JavaScript by gray_-_wolf on Sunday March 31, 2024 @03:17PM (#39887174)
Maybe a stupid question, but isn't the memory released anyway when I close the tab? So why do memory leaks matter?
Re:A proposal to add signals to JavaScript by zdragnar on Sunday March 31, 2024 @03:45PM (#39887408)
It depends on how much you're leaking, and how fast.

Best case scenario, it just slows down garage collection a little bit, as you're holding into a lot of references that aren't going anywhere.

On the other hand, I recall a bug in a particular version of AngularJS where component DOM nodes wouldn't get cleaned up when navigating with the router unless you manually set all of the scope values their templates used to null.

We had a data dense application with tables and what not, and you could clearly watch memory jump tens or more megabytes flipping between pages in the chrome dev tooling.

Eventually (this was a SPA intended to be used for upwards of hours at a time) the page would crash.

Re:A proposal to add signals to JavaScript by Xenoamorphous on Sunday March 31, 2024 @04:02PM (#39887546)
Have you ever seen Chrome’s “aw, snap!” screen (if you use Chrome)?

More often than not that’s due to a memory leak.

Re:A proposal to add signals to JavaScript by dr_kiszonka on Sunday March 31, 2024 @03:39PM (#39887349)
Not a web dev person, but some "tabs" have a very long lifetime, e.g., webmail clients, Whatsapp, etc.
Re:A proposal to add signals to JavaScript by leptons on Sunday March 31, 2024 @03:44PM (#39887391)
The problem is if you don't close the tab, the memory leak can cause that one tab's memory to balloon to 1GB or more because memory isn't being released, when that tab should only be consuming 50MB.
Re:A proposal to add signals to JavaScript by chrisweekly on Sunday March 31, 2024 @11:36PM (#39890704)
Not "stupid", but maybe hasty / shallow? Many SPAs are long-running, and memory leaks can accrue quickly, destroying performance.
Re:A proposal to add signals to JavaScript by ivan_gammel on Sunday March 31, 2024 @03:01PM (#39887038)
Did you read the document? They have an example there, which is quite similar to yours, and explain what is the problem.
Re:A proposal to add signals to JavaScript by explaininjs on Sunday March 31, 2024 @03:05PM (#39887060)
No, they don't. In fact, if you search "event" in the proposal you get exactly one result, the prefix of "eventually". This is a serious shortcoming of the proposal that should be addressed.
Re:A proposal to add signals to JavaScript by throwitaway1123 on Sunday March 31, 2024 @03:11PM (#39887118)
I think the comment you're replying to is referring to the pub/sub sections of the proposal. They don't explicitly mention events, but events are a subset of the publish/subscribe pattern.
Re:A proposal to add signals to JavaScript by explaininjs on Sunday March 31, 2024 @03:14PM (#39887138)
But then so are signals.

The only "benefit" signals as proposed here give you is less control over the exact dispatch pattern of the graph, for instance things like debouncing, throttling, batching, etc etc etc. Aka all the things you absolutely must have control over if you want to make something resembling a high performance application.

Re:A proposal to add signals to JavaScript by naasking on Sunday March 31, 2024 @03:25PM (#39887250)
Signals are not a subset of events. Signals combine event subscription with value construction, which promotes a remote declarative model for updates.

> The only "benefit" signals as proposed here give you is less control over the exact dispatch pattern of the graph, for instance things like debouncing, throttling, batching,

Events don't give you any more control over those properties than signals, they just require more boilerplate.

Re:A proposal to add signals to JavaScript by ivan_gammel on Sunday March 31, 2024 @03:12PM (#39887124)
Oh, come on. They do have an example of architecture, not literal example of events. It doesn’t matter what trivial implementation of Observer pattern you choose.
Re:A proposal to add signals to JavaScript by explaininjs on Sunday March 31, 2024 @03:15PM (#39887153)
Except one is already built into the language? And it provides all the upsides of signals with none of the downsides? (Modulo proper use of `using` directives)
Re:A proposal to add signals to JavaScript by ahmedfromtunis on Sunday March 31, 2024 @03:10PM (#39887109)
Can you please point to where in the document such an example was mentioned? I rechecked the document and couldn't find it.
Re:A proposal to add signals to JavaScript by ivan_gammel on Sunday March 31, 2024 @03:17PM (#39887168)
Just look for the example of a design pattern („Example - A VanillaJS Counter“ section), not for a literal implementation of it via events. Conceptually they are the same.
Re:A proposal to add signals to JavaScript by nurple on Sunday March 31, 2024 @03:55PM (#39887499)

  Welcome to Node.js v21.6.2.
  Type ".help" for more information.
  > window.dispatchEvent(new Event('counterChange'))
  Uncaught ReferenceError: window is not defined
Re:A proposal to add signals to JavaScript by runarberg on Sunday March 31, 2024 @04:05PM (#39887569)

    $ node
    Welcome to Node.js v20.6.1.
    Type ".help" for more information.
    > const target = new EventTarget()
    undefined
    > target.dispatchEvent(new Event("counterChange"))
    true
Re:A proposal to add signals to JavaScript by nurple on Sunday March 31, 2024 @04:37PM (#39887865)
tyvm!
Re:A proposal to add signals to JavaScript by extheat on Sunday March 31, 2024 @10:40PM (#39890389)
Even better on Node, you have EventEmitter. A much simpler interface.
Re:A proposal to add signals to JavaScript by LittleDan on Sunday March 31, 2024 @04:41PM (#39887900)
LGTM! Smells like Redux (in a good way). But then ultimately at the root you probably want the event to update your “model”, and then that leads to an update of the “view”. This is the part where signals can be useful.
Re:A proposal to add signals to JavaScript by Offler on Monday April 01, 2024 @07:40AM (#39893055)
Look at legend-state, it's most definitely not Redux (in a good way IMO).
Re:A proposal to add signals to JavaScript by briantakita on Sunday March 31, 2024 @04:49PM (#39887956)
> Anything wrong with that?

It only works in browser environments.

Re:A proposal to add signals to JavaScript by lelandfe on Sunday March 31, 2024 @06:46PM (#39888852)
Re:A proposal to add signals to JavaScript by briantakita on Monday April 01, 2024 @10:49AM (#39894717)
Browser environments don't have EventEmitter. Different event APIs between browsers & nodejs. A library (3rd party or custom) is needed to make event code isomorphic.
Re:A proposal to add signals to JavaScript by kabes on Sunday March 31, 2024 @05:55PM (#39888419)
Signals are also just pub/sub, but with a more ergonomic api. More ergonomic because listeners are added and released automatically.

It can also be more performant, eg, say you have a computation that depends on 2 values:

`result = a ? b : 0`

Then if a is falsy, we don't need to recompute if b changes. This is achieved automatically with signals, but would require quite some code with classic pub/sub.

Re:A proposal to add signals to JavaScript by fwlr on Sunday March 31, 2024 @06:00PM (#39888457)
If you mis-type ‘countenChange’ it could be quite frustrating!
Re:A proposal to add signals to JavaScript by everybackdoor on Sunday March 31, 2024 @06:05PM (#39888497)
In 2024 we have linters and other static analysis tools for catching these kinds of things right in the IDE.
Re:A proposal to add signals to JavaScript by berkes on Sunday March 31, 2024 @06:11PM (#39888540)
If that truly is your reason to choose or forego a software design pattern, than what the h. are you doing with JavaScript?
Re:A proposal to add signals to JavaScript by 6510 on Sunday March 31, 2024 @10:59PM (#39890503)
You have to name the function or you cant remove it :P
Re:A proposal to add signals to JavaScript by unrealhoang on Monday April 01, 2024 @11:27AM (#39895151)
The problem with events handling are, you don't actually know what needs to be done when the event trigger. Let's say you have 20 components, on counterChange, which of the 20 components need to be updated? And how? You can either do it the simple (and very inefficient), and it's React conceptually way by render all 20 of your components again with new value of counter, i.e.

    window.addEventListener('counterChange', () => {
        element.innerHTML = 20components.map(|c| c.renderHTML(newCounterValue)).join('');
    });
or, you have to check the components on case by case basis on a. if the component need to be updated or not, and b. how is the most efficient way to update such component. And in TFA, if counter is changed from odd to odd, the label doesn't need to be updated.

Also, multiply the number of events to the number of components can make the application go out of hand very quickly.

Re:A proposal to add signals to JavaScript by mg on Monday April 01, 2024 @11:30AM (#39895195)
If the component only wants to rerender when the counter changes from odd to even or even to odd, it can cache the value and do as it pleases.
Re:A proposal to add signals to JavaScript by troupo on Monday April 01, 2024 @04:31PM (#39898889)
But then you have to make sure that the element caches that value. With signals you don't have to do that. Your component (or parts of it) will never be re-rendered if it never uses the signal.
Re:A proposal to add signals to JavaScript by febed on Monday April 01, 2024 @12:30PM (#39895955)
Very hard to debug as the application gets larger
Re:A proposal to add signals to JavaScript by uzerfcwn on Monday April 01, 2024 @03:55PM (#39898436)
As an end user, I love when web applications pass events through the DOM tree, because it allows me to easily create plugins by hooking on the same events. Youtube is a prime example of how to do things right.

Unfortunately, modern frameworks really want to use their own event channels, which makes hooking a pain.