How I Like to Write JavaScript

Rate this content
Bookmark

I love writing JavaScript. It feels lightweight, free-form, and flexible--all qualities that boost creativity and invite me to practice new and interesting techniques. Over time, I've developed lots of patterns and principles that help me day to day. In this talk, I'll show you a handful of them and then we'll look at how I apply them inside the AlpineJS codebase itself. It's gonna be a good time!

This talk has been presented at JSNation 2023, check out the latest edition of this JavaScript Conference.

FAQ

Alpine JS is a JavaScript framework created by Caleb Porzio that allows developers to add dynamic functionalities to HTML elements directly through attributes like click listeners.

Hot JS was created as a tiny, scrappy version of Alpine JS during a demonstration by Caleb Porzio to illustrate the process of building, making a mess, and then refactoring JavaScript code to improve maintainability.

The DOM Walker is a script that iterates through every element on a webpage, allowing the script to check for specific attributes like 'flame click' and initialize them accordingly.

The Mutation Observer API in JavaScript is used to observe changes to the HTML structure, such as attributes modifications. It helps in dynamically detecting and responding to changes without reloading the page.

Caleb Porzio emphasizes the use of guard clauses to simplify conditionals, extracting code into functions for better organization, and designing by wishful thinking to write cleaner, more maintainable code.

The 'on' function adds an event listener to an element and returns a cleanup function, allowing for efficient management of events and ensuring that event listeners can be properly removed when no longer needed.

Directive registration allows developers to declare and manage custom directives that define how attributes on HTML elements should be handled, thereby organizing code and facilitating easier modifications and maintenance.

Caleb Porzio
Caleb Porzio
26 min
05 Jun, 2023

Comments

Sign in or register to post your comment.
Video Summary and Transcription
Caleb Porzio introduces Alpine JS, a JavaScript framework, and demonstrates the process of creating a scrappy version of AlpineJS and refactoring it. The Talk covers topics such as creating a Dom Walker, evaluating expressions, using mutation observers, and refactoring the code. It also discusses techniques like inverting conditionals, using callbacks, and parameter currying. The Talk emphasizes the importance of abstraction, handler extraction, and a declarative approach in software development.
Available in Español: Cómo me gusta escribir JavaScript

1. Introduction to Alpine JS

Short description:

Hey, my name is Caleb Porzio. I made a JavaScript framework called Alpine JS. We're going to create a scrappy version of AlpineJS, make a mess, then refactor it using techniques from Alpine.

Hey, my name is Caleb Porzio. I made a JavaScript framework called Alpine JS. And when I first started AlpineJS, I was by no means a killer JavaScript developer, but it's been a few years. I've rewritten the code base a few times, and now I have a bunch of opinions that I think help me make more maintainable code bases that I actually want to work in.

So we're going to create this tiny scrappy version of AlpineJS today, and we're going to basically make a mess doing it, then we'll walk it back and refactor it using some of the techniques that I've used inside Alpine. So let's do it.

2. Creating the Dom Walker and Handling Flame Click

Short description:

Here is a button on a page with a script tag with nothing in it. We're going to create a little playground. Instead of using Alpine's exon click, we'll use flame click and write JavaScript inside it. Let's create a Dom Walker script to look for flame click attributes and initialize them. We'll check if an element has the flame click attribute and get its contents.

Here is a button on a page with a script tag with nothing in it. This is going to be our little playground. And the framework we're going to write is, I don't know if you've seen Alpine, but with Alpine, you can add things like click listeners directly to buttons by adding attributes directly in the HTML, like exon click. Well, instead of that, we're going to do flame click, and then we can write any JavaScript in here. So let's write something like so hot.

Okay. And now if we load this in the browser, nothing is going to happen. We have this button with click alert. So hot, we click it and nothing happens because we haven't written any JavaScript for it. So let's do that. So the first thing I would do is create a little Dom Walker, a little script that'll walk through every element on the page and give us an opportunity to look for things like flame click and actually initialize them. So let's write a Dom Walker. And with the magic of snippets, you don't have to sit here and watch me write a little Tom Walker. So here's the Walker script. And this is the point where we have this little variable called L. Which every iteration in this while loop is just going to walk the next node. So let's just console log out L and refresh the page and make sure that it works. If we look at the console, here it is. We have button, click me. Now we have three buttons on the page. Let's refresh, make those three. And it's going to, it's going to walk through all those three. If we had a button nested inside of a div, it would walk that div as well. And then the button inside of it. Okay, great. So we have our little Dom Walker. Now in this part, we can do stuff with every element. And in our case, we want to check for the existence of this flame click attributes, we'll say if L dot has attribute flame, click, then let expression equal L dot get attribute flame click. So this is going to get the contents of that attribute. Okay.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Building Better Websites with Remix
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Top Content
Remix is a web framework built on React Router that focuses on web fundamentals, accessibility, performance, and flexibility. It delivers real HTML and SEO benefits, and allows for automatic updating of meta tags and styles. It provides features like login functionality, session management, and error handling. Remix is a server-rendered framework that can enhance sites with JavaScript but doesn't require it for basic functionality. It aims to create quality HTML-driven documents and is flexible for use with different web technologies and stacks.
Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced 2023React Advanced 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
Watch video: React Compiler - Understanding Idiomatic React (React Forget)
Joe Savona
Mofei Zhang
2 authors
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Watch video: Speeding Up Your React App With Less JavaScript
Mishko, the creator of Angular and AngularJS, discusses the challenges of website performance and JavaScript hydration. He explains the differences between client-side and server-side rendering and introduces Quik as a solution for efficient component hydration. Mishko demonstrates examples of state management and intercommunication using Quik. He highlights the performance benefits of using Quik with React and emphasizes the importance of reducing JavaScript size for better performance. Finally, he mentions the use of QUIC in both MPA and SPA applications for improved startup performance.
Full Stack Documentation
JSNation 2022JSNation 2022
28 min
Full Stack Documentation
Top Content
The Talk discusses the shift to full-stack frameworks and the challenges of full-stack documentation. It highlights the power of interactive tutorials and the importance of user testing in software development. The Talk also introduces learn.svelte.dev, a platform for learning full-stack tools, and discusses the roadmap for SvelteKit and its documentation.
SolidJS: Why All the Suspense?
JSNation 2023JSNation 2023
28 min
SolidJS: Why All the Suspense?
Top Content
Suspense is a mechanism for orchestrating asynchronous state changes in JavaScript frameworks. It ensures async consistency in UIs and helps avoid trust erosion and inconsistencies. Suspense boundaries are used to hoist data fetching and create consistency zones based on the user interface. They can handle loading states of multiple resources and control state loading in applications. Suspense can be used for transitions, providing a smoother user experience and allowing prioritization of important content.

Workshops on related topic

Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Top Content
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
Building WebApps That Light Up the Internet with QwikCity
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Miško Hevery
Miško Hevery
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
Back to the Roots With Remix
React Summit 2023React Summit 2023
106 min
Back to the Roots With Remix
Featured Workshop
Alex Korzhikov
Pavlik Kiselev
2 authors
The modern web would be different without rich client-side applications supported by powerful frameworks: React, Angular, Vue, Lit, and many others. These frameworks rely on client-side JavaScript, which is their core. However, there are other approaches to rendering. One of them (quite old, by the way) is server-side rendering entirely without JavaScript. Let's find out if this is a good idea and how Remix can help us with it?
Prerequisites- Good understanding of JavaScript or TypeScript- It would help to have experience with React, Redux, Node.js and writing FrontEnd and BackEnd applications- Preinstall Node.js, npm- We prefer to use VSCode, but also cloud IDEs such as codesandbox (other IDEs are also ok)
Integrating LangChain with JavaScript for Web Developers
React Summit 2024React Summit 2024
92 min
Integrating LangChain with JavaScript for Web Developers
Featured Workshop
Vivek Nayyar
Vivek Nayyar
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.