Connect with us

Code

Differences Between Includes and Joins in Ruby on Rails

Published

on

ashubhosale Hacker Noon profile picture

@ashubhosaleashubhosale

I am here to write about my experiences and how I learnt from my experiences.

Many of us know about includes, joins but sometimes we confuse about their usage. As I was experimenting with code refactoring in one of my projects, there I have tried these things. So I thought I can share these findings with you guys.

As we know includes and join are used when we are performing operations on associated tables. Both are used for the same purpose.

Includes: Uses eager loading, When we want to fetch data along with an associated table then includes must be used.

Joins: Uses lazy loading. We can use joins when we want to consider the data as a condition from the joined table but not using any attributes from the table.

I will show you an example where includes is preferred instead of joins, also I have benchmarked both the queries so that you can see which is faster!!!


class Item < ApplicationRecord belongs_to :user end class User < ApplicationRecord has_many :items, dependent: :destroy
end

Now I want to display the item title with the user’s first name.

Using includes the query output will be,

puts Benchmark.measure {
items = Item.includes(:user)
items.each do |item| item.title item.user.first_name
end
}

Using joins query output will be,

puts Benchmark.measure {
items = Item.joins(:user)
items.each do |item| item.title item.user.first_name
end
}

So it’s self-explanatory, that include is preferred. But if we want to have items where user_id: 1, and we are not displaying any data from User table, then only use joins, because this will not load any user’s data until we want(lazy load). As given below.

items = Item.joins(:user).where(user_id: 1)
items.each do |item| item.title
end

Below are some reference links. You can watch them for your understanding:

http://railscasts.com/episodes/181-include-vs-joins?autoplay=true

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.

Coinsmart. Beste Bitcoin-Börse in Europa
Source: https://hackernoon.com/differences-between-includes-and-joins-in-ruby-on-rails-1r2s35oj?source=rss

Code

Developing An App with NodeJS: Best Practices to Follow

Published

on

Riya Thomas Hacker Noon profile picture

@riya-thomasRiya Thomas

I am currently working as a developer.

In the present scenario, NodeJS has become one of the most popular platforms to develop high-quality applications. Its open-source, cross-platform, JavaScript runtime environment and sublime features make it an excellent option for developers and product owners.

Although app development companies have been using it for quite a long time, NodeJS is relatively new. Many still do not know about its particular features and the benefits they can have after learning them. This article will help you understand the NodeJS best practices to help you develop a top-class application. So, let’s get started.

Seven Best NodeJS Practices You Should Know About

Prepare a well-defined structure for your Project

While developing an app, it can be challenging to manage a massive codebase with hundreds of dependencies. Therefore, it is better to divide and organize your code into small chunks and put them into a separate folder or codebase. Make sure that each unit is kept small and simple.

One of the best ways to do this is to design a small piece of software and divide the whole stack into independent components that do not share files with each other. In simple terms, you can have different modules to address various concerns pertaining to your application. These different modules can cater to and respond to different aspects of the client requests at the client-side. The folder structuring can also help structure and organize the code to make it clearer and more readable, easing the app development process.

Avoid Mutation in the original array.

Mutation happens when we change a JavaScript Array or object without creating a new variable or re-allocating the existing one. In JavaScript, everything is referenced. It means if you mutate an array or object in JS, it will mutate the original array/object.

Mutation can cause a lot of errors while developing an app. It may lead to unpredictable and hard-to-debug errors where data becomes incorrect somewhere, and you have no idea how and where it happens.

Make code harder and complex to understand. At any instant, the value of an array or object might change and differ. Hence, you need to be careful while reading the values in the code.

Consider this through the example code below. The first one will mutate the original array, and hence, you might encounter unforeseen bugs later.

const elements = [5,3,4,10,2];
const results = elements.sort().map(element=> element*2);
const elements = [5,3,4,10,2];
const results = [...elements].sort().map(element=> element*2);

In the second code, we create a copy of the element array, and that’s why it’s not affecting the original one.

Use a standard Style Guide

There can be times when you open a new file from a new project for the first time or get a file from a different developer. You spend the next few hours understanding the code, reformatting the braces, changing tabs from spaces, etc. This might take a lot of your time and stretch the process of app development.

To prevent this from happening and understanding the code easily, it is better to use a consistent coding style. For this purpose, you can use JavaScript linter tools like ESLint, which is a de-facto standard for checking common programming errors and fixing code style. Other tools like Prettier and Beautify help format the fixes and work parallelly with ESLint.

Prefer Const/Let over Var

When you use const in a code and assign a variable, you can not reassign it. Using const will prevent you from getting tempted to use the same variable for multiple uses, making your code clearer. If you think you need to reassign a variable, for instance, in a for loop, you can use let to declare it. When you declare a variable using let, it will only be available in the block scope in which it was defined. 

On the other hand, Var is function scoped not block-scoped, which means you can not declare variables inside the blocks making it more error-prone. Let’s understand this through an example:

console.time('timer')
for(var i =0; i<999999; i++){}
console.timeEnd('timer')
// timer: 7.90380859375 ms
console.time('timer')
for(let i =0; i<999999; i++){}
console.timeEnd('timer')
// timer: 3.73779296875 ms

Both the codes are almost identical in terms of logic. However, the second code (using let) will be nearly twice as fast as the first code (using var). This is because the scope of let and const is local to the blocks in which they are declared, while var creates the instance in the global scope. Therefore, we have to traverse the whole global object to access it, which is both time-consuming and error-prone.

Use Dependency Injection

You might not be aware that NodeJS comes up with unique features and NodeJS security best practices to make the programming and production of your application easy. However, working with dependencies (services) can be cumbersome due to the issues you can face while managing and testing the code.

But no worries, as there’s a solution for that too, and it’s called dependency injection. It is a software design pattern in which you can inject or pass one or more dependencies (or services) by reference, into a dependent object. With dependency injection, you can:

  • Make the unit testing process streamlined and well-organized.
  • Speed up your git-flow.
  • Avoid purposeless module coupling.

Always use Asynchronous code

NodeJS is known for its asynchronous nature. JavaScript offers callback functions (functions that pass as an argument to other functions). These functions also allow you to describe the asynchronous behavior in JavaScript. However, when you overuse raw callback (like async-await), it affects the application control flow, disturbs error handling and semantics that is more similar to synchronous code. The issue with synchronous code is that it blocks any other code from running until the former code gets completed.

On the other hand, asynchronous code keeps your code free from blockages and allows you to run things in parallel. Therefore, you should use asynchronous code wherever possible, and to make it possible, ES 6 (ECMASCRIPT 2015) came out with the Promises. It makes your code easier to read and test while providing a better error handling platform and functional programming semantics. Let’s understand this concept more clearly through an example.

console.time('timer')
for(var i =0; i<999999; i++){}
console.timeEnd('timer')
// timer: 7.90380859375 ms
console.time('timer')
for(let i =0; i<999999; i++){}
console.timeEnd('timer')
// timer: 3.73779296875 ms

Here we are running three blocks of code. Suppose one function takes one second; running your code with example 1 will take 3 seconds. On the other hand, in example 2, we are executing the same three functions, but this time it is asynchronous and will take nearly 1 second only. These will help in enhancing your code performance and help a lot in the production of the app.

Conduct Unit testing and Final testing

Testing is undoubtedly a crucial stage in every project. The entire flow of the project, not just the outcome, depends on testing since buggy code can slow down the app development process and cause other troubles too.

The best way to test your application is to test them by units. The primary goal of the unit testing is to pick out a section, isolate it and verify for its correctness. Unit testing can help in:

  • Enhancing code quality
  • Detection of errors in the earlier stage
  • Development cost reduction

Unit testing helps the programmers detect the faults in the project’s different parts in the earlier stages. After completing the app development process, you need to perform final testing of your application to ensure that it is ready for launch. There are many things you can check for, such as:

  • Running your app in production mode
  • Enabling Gzip compression
  • Using a load balancer like Enginx
  • Accessing PM2 to manage your NodeJS application on Server
  • Using clustering to create multiple instances of your application
  • Implementing rate-limiter in your APIs like express-rate-limiter

Testing all these checkpoints will help in boosting up your app’s performance and creating a robust NodeJS application.

Wrapping Up

This article introduced you to the top NodeJS best practices with which you can develop an app in less time and with reduced effort. Although there can be more such practices for an excellent app development process, we tried to present you with the most widely used and standard ones. Since now you know enough about developing an app with NodeJS, go ahead and implement your knowledge. You can also hire NodeJS developers
and discuss the practices and concepts of your app to get a mind-blowing application for your business.

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.

Coinsmart. Beste Bitcoin-Börse in Europa
Source: https://hackernoon.com/developing-an-app-with-nodejs-best-practices-to-follow-zby37hw?source=rss

Continue Reading

Code

Best Online Code Editors To Use In 2021🚀

Published

on

Saanvi Sen Hacker Noon profile picture

@saanvi-senSaanvi Sen

We built high quality, highly customizatable Bootstrap Admin Templates. https://themeselection.com

Are you looking for the Best Online Code editors? Then here is the collection of Best Online Code Editors For Web Developers.

What is an online code editor?

An online code editor is a tool that resides on a remote server and is accessible via browsers. Some online code editors have basic features more similar to text editors while others are like complete IDEs. In this article, we will review both types.

Some online code editors focus on one language or even a framework. For example, there are products that call themselves – JavaScript online code editors or react online editors.

As a developer, your main tool is obviously the one that allows you to turn your ideas into code: A text editor. As time goes by, more online text editors are created that can help you code from any computer with Internet access. In this article, let’s take a look at 10+ useful online code editors.

Following are the major advantages of using online code editors

  • Zero setups. You won’t have to download, install and configure an IDES
  • Sharing and Collaboration. Start coding and then forward the URL to your colleague to continue your work or help you debug it
  • Zero or little cost. The vast majority of online code editors have free versions that will be enough for you for most of the daily tasks
  • Subscription-based pricing. It might be very useful to pay monthly for online editors instead of yearly licenses.

How to choose an online code editor?

Most famous online code editors share many great features. These include autocompletion, Git integration, plugin support, CI/CD pipelines, and others. But it’s the little things that can make a specific editor a better fit for you than others.

Let’s run through some aspects you need to keep in mind choosing an online IDE/code editor:

  • How fast an application works
  • Languages support
  • For free editors: how many ads it shows
  • Ease of setup
  • Integrations with repository managers
  • NPM support
  • A number of text and layout settings
  • Terminal support

Before you start the collection, Check Vuexy – Vuejs, React, Angular, HTML & Laravel Admin Dashboard Template and Chameleon Free Bootstrap Admin Template

Now, let’s begin the collection..!!

StackBlitz claims to allow you to code the future in your browser. And after trying it, I’m confident you’ll agree that this web application is extremely useful for coders.

StackBlitz features 5 workspaces: React, AngularJS, JavaScript, Ignite UI, and KendoReact. Once launched, you will notice a similarity between StackBlitz and the VSCode editor, which is a good thing if you’re used to Microsoft’s editor.

Another extremely cool StackBlitz feature is that all applications get deployed automatically on their servers, and hosted for free.

Features:

  • Native support for Firebase (which is something I don’t personally use, but hey, it’s a boon for those not wanting to dive into the murky depths of the backend)
  • Intellisense, Project Search
  • Hot reloading as you type
  • Import npm packages
  • Edit offline when not connected!

Probably the most popular online code editor. CodePen is fast, easy to use, and allows a web developer to write and share HTML/CSS/JS code online. CodePen is free and creating an account isn’t mandatory, so you can start writing code and create a new web application straight from your web browser quickly and efficiently.

CodePen editor allows you to use Vim Key Bindings which are command-line keyboard shortcuts. Both of these tools together can help to create a faster workflow.

Features:

  • File system
  • Autocomplete
  • Private sandboxes
  • Website deployment
  • Collaboration mode

CodeSandbox can be thought of as a much more powerful and complete take on JSFiddle. True to its name, CodeSandbox provides a complete code editor experience and a sandboxed environment for front-end development.

This complete development environment is loaded with many features and code templates that will definitely make your coding faster and easier.

Features:

  • Npm support: Yes, you can add pretty much any package that is available on npm.
  • Files, folders, modules: You can split your code into multiple files, add/remove images from the public folder, and build/import modules as you see fit. The workflow mirrors that of a modern module bundler, so you don’t need to set up (almost) anything.
  • Support for TypeScript, hot reloading, GitHub export, static file hosting, etc.
  • It is built on Monaco editor, the same beast that powers the favorite VSCode editor. This brings powerful features like “Go To,” “Find References,” and necessary refactoring to your fingertips!
  • Snippet support for Emmet
  • Integrated DevTools, linting, error overlays, testing frameworks (Jest), keybindings, and more.
  • Powerful CLI to directly import local projects into CodeSandbox.

While JSFiddle can’t replace a full-fledged text editor, it does a damn good job of handling one-off frontend scripts. It’s so popular that Q&A sites like StackOverflow already support the embedding of JSFiddle links directly in their platform.

Advantages:

  • Free to use (no hidden fee or freemium features).
  • JSFiddle supports itself through ads (at least as of writing), and you can see an Adobe ad in the lower left of the screenshot above.
  • Code collaboration features — ideal for building concepts together, interviews, etc.
  • Multiple layouts, font sizes, light/dark themes, etc.Code formatting (tidying), upcoming support for linters (CSS and JS), and more

JSBin is an online text editor primarily focused on Javascript, with a fast and simple interface. Each of your code snippets can be tested through your web browser, and then exported into a text file.

Another good thing to note is that JSBin can import popular HTML/CSS/JS frameworks such as jQuery and Bootstrap, allowing you to easily create modern pages and web applications.

Features:

  • Live reload both in the editor and in full preview
  • Codecasting – blog postConsoleFull unmodified rendered view
  • Gist support: import and exportProcessors. HTML. CSS. Sass & SCSS (with Compass & Bourbon)
  • Debug/source mode

Gitpod is a refreshing take on cloud code editors (or IDEs, if you will) that aims to keep your code always tested and up to date. In other words, it’s deeply integrated with GitHub, and every time you add code, it runs your testing and CI/CD pipelines to make sure code is always at 100% health.

Worth checking out if you love the VSCode experience and want something that supports all major back-end/front-end languages and frameworks

Dev environments as code – Gitpod applies lessons learned from infrastructure-as-code. Spinning up dev environments is easily repeatable and reproducible empowering you to automate, version-control, and share dev environments across your team.

Features:

  • Prebuilt dev environments
  • Integrated Docker build
  • GitLab, GitHub, and Bitbucket integration
  • Integrated code reviews
  • Collaboration

Codespaces is a configurable cloud development environment available in your browser on GitHub or through Visual Studio Code. A codespace includes everything developers need to develop for a specific repository, including the Visual Studio Code editing experience and common languages, tools, and utilities

If you’re a die-hard SOLID fan and a nit-picking software architect, the Theia IDE will tickle your separation-of-concerns bone. It’s a TypeScript-coded (five points for style straightaway!) code IDE that has a perfectly separate front-end and backend. The front-end runs in a browser, while the backend can be anywhere — local machine or the cloud!

But that’s not all — the front-end can be run as an Electron app with a fully functional, isolated browser environment, giving you the look-and-feel of a native desktop app should you crave it.

Features:

  • Establish a platform to build IDE-like products.
  • Provide the end-user with a full-fledged multi-language IDE (not just a smart editor)
  • Support equally the paradigm of Cloud IDE and Desktop IDE.
  • Provide support for multiple languages via the language and debug server protocols.

Coder is a VSCode environment bundled in a server that can be run locally or in the cloud. The recommended configuration is to run the IDE as a server in the cloud and access it locally via the browser. There are prebuilt Docker images for zero-hassle setups, and an enterprise plan should you need support or have different needs.

Cloud9 was arguably the first browser-based IDE that offered serious features and took the idea of browser-as-an-editor mainstream. No wonder that Amazon later acquired it, and today, Cloud9 is part of the AWS offerings.

There are no additional charges for using Cloud9. You can connect Cloud9 to an existing/new AWS compute instance, and you pay only for that instance. It’s also possible to connect to a third-party server over SSH — for exactly no fee

Features:

  • First-class support for AWS
  • Serverless applications (debugging, etc.)
  • Direct terminal access to AWS from within the editor
  • Over 40 programming languages supported (Go, C++, Ruby, Node, Python, PHP, Java . . . take your pick)

Replit is a free, collaborative, in-browser IDE to code in 50+ languages. It is the best tool for quickly starting, sharing, and developing projects in any programming language, right from your browser. On Replit, there is no “deployment” stage of your projects– we instantly host all of your repls.

Features:

  • In browser IDE
  • GitHub integration
  • API and Plugins
  • Host and Deploy

Glitch is a new coding website from Fog Creek Software (which built Trello and FogBugz and is led by tech entrepreneur Anil Dash) with a simple goal: to provide “a friendly community where you’ll build the app of your dreams.”

There’s no need to reconfigure your machine and no deployment setup — as soon as you create a new project, your Glitch app is live. Share or embed it anywhere. You can even add a custom domain to make it your own. Glitch handles all the setup so you can focus on building your new app.

Conclusion:

This was the collection of the best online code editors for web developers in 2021. This is of course not a complete list, as there are many other online code editors available on the internet that you can use. We have collected these online editor tools by their popularity. Pick any of them as per your need and requirements.

Do not forget to bookmark and share this collection.

Also published at https://dev.to/theme_selection/best-online-code-editors-for-web-developers-5bpn

by Saanvi Sen @saanvi-sen. We built high quality, highly customizatable Bootstrap Admin Templates. https://themeselection.comRead my stories

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.

Coinsmart. Beste Bitcoin-Börse in Europa
Source: https://hackernoon.com/best-online-code-editors-to-use-in-2021-8p1q327n?source=rss

Continue Reading

Code

Introducing The Web Animations API and @okikio/animate

Published

on

Okiki Ojo Hacker Noon profile picture

@okikioOkiki Ojo

I am currently a student and part-time web dev, if you need a hand on any project, I would be happy to help.

The Web Animations API lets us construct animations and control their playback with JavaScript. The Web Animations API opens the browser’s animation engine to developers and manipulation by JavaScript. This API was designed to underlie implementations of both CSS Animations and CSS Transitions and leaves the door open to future animation effects. It is one of the most performant ways to animate on the Web, letting the browser make its own internal optimizations without hacks, coercion, or window.requestAnimationFrame().

With the Web Animations API, we can move interactive animations from stylesheets to JavaScript, separating presentation from behavior. We no longer need to rely on DOM-heavy techniques such as writing CSS properties and scoping classes onto elements to control playback direction. And unlike pure, declarative CSS, JavaScript also lets us dynamically set values from properties to durations. For building custom animation libraries and creating interactive animations, the Web Animations API might be the perfect tool for the job. Let’s see what it can do! 

For the rest of this article, I will sometimes refer to the Web Animation API as WAAPI. When searching for resources on the Web Animation API on Google, Bing, etc… you can often be led astray by the search query “Web Animation API” so, to make it easy to find resources, I feel we should adopt the term WAAPI; tell me what you think in the comments below.

@okikio/animate

@okikio/animate is an animation library for the modern web. It was inspired by animateplus, and animejs; @okikio/animate is a Javascript animation library focused on performance and ease of use. It utilizes the Web Animation API to deliver butter-smooth animations at a small size, it weighs ~5.36 KB (minified and gzipped).

What is the story behind @okikio/animate?

In 2020, I decided to make a more efficient PJAX library, similar to Rezo Zero’sStarting Blocks project, but with the ease of use of barbajs. I felt starting blocks was easier to extend with custom functionality, and could be made smoother, faster, and easier to use. (Note: if you don’t know what a PJAX library is I suggest checking out MoOx/pjax; in short PJAX allows for smooth transitions between pages using fetch requests and switching out DOM Elements).

I started the project, over time my intent shifted, I started noticing how often sites from awwwards.com used PJAX, but often they butchered the natural experience of the site and browser, alot of the sites that featured PJAX look cool at first glance, but actual usage was a different story, scrollbars were often overridden, prefetching was often too eager, and the sites almost never prepared for people who didn’t have powerful internet connections, CPU’s and/or GPU’s. So, I decided that for the library I was going to build everything was going to be progressively enhanced. I started what I call the native initiative stored in the Github repo okikio/native; a means of introducing all the cool and modern features in a highly performant, compliant, and light-weight way.

For the native initiative I designed the PJAX library @okikio/native; while testing on an actual project I realized there were no libraries that took advantage of it, so, I developed @okikio/animate (Note: this was in 2020, around the same time use-web-animations by wellyshen was being developed. If you are using react and need some quick animate.css like effects, use-web-animations is a good fit). At first it was just supposed to be simple wrapper, but little by little I built on it, and it’s now at 80% feature parity with more mature animation libraries.

Note: you can read more on the native initiative as well as the @okikio/native library on the Github repo okikio/native. Also, okikio/native, is a monorepo with @okikio/native & @okikio/animate being sub-packages within it.

How does @okikio/animate fit in?

The Web Animation API is very open in design, it is functional on its own but it’s not the most developer-friendly or intuitive API, so, I developed @okikio/animate to act as a wrapper around the WAAPI, to introduce the features you know and love from other more mature animation libraries (with some new features included) to the high-performance nature of the Web Animation API.

Getting Started

@okikio/animate is heavily inspired by animejs and animateplus, as such it uses a very similar format.

@okikio/animate creates animations by creating new instances of Animate (a class that acts as a wrapper around the Web Animation API), 


import { Animate } from "@okikio/animate"; new Animate({ target: [/* ... */], duration: 2000, // ... 
});

The Animate class receives a set of targets to animate, it then creates a list of WAAPI Animation instances, alongside a main animation (the main animation is a small Animation instance that is set to animate the opacity of a non-visible element, it exists as a way of tracking the progress of the animations of the various target elements), the Animate class then plays each target elements Animation instance, including the main animation, to create butter-smooth animations.

The main animation is there to ensure accuracy in different browser vendor implementations of WAAPI. The main animation is stored in Animate.prototype.mainAnimation, the target elements Animation instances are stored in a WeakMap, with the key being its KeyframeEffect, you can access the animation for a specific target using the Animate.prototype.getAnimation(el).

You don’t need to fully understand the prior sentences, but they will aid your understanding of what @okikio/animate does. If you want to learn more about how WAAPI works check out MDN, or if you would like to learn more about the @okikio/animate library I’d suggest checking out the Github project, okikio/native.

Usage, Examples & Demos

By default, needing to create a new instance of Animate is very annoying, so, I created the animate function, which creates new Animate instances every time it’s called.


import animate from "@okikio/animate";
// or
import { animate } from "@okikio/animate"; animate({ target: [/* ... */], duration: 2000, // ... 
});

When using the @okikio/animate library to create animations you can do this:

import animate from "@okikio/animate"; // Do note, on the web you need to do this, if you installed it via the script tag:
// const { animate } = window.animate; (async () => { let [options] = await animate({ target: ".div", // Units are added automatically for transform CSS Properties translateX: [0, 300], duration: 2000, // In miliseconds speed: 2, }); console.log("The Animation is done...");
})();

Check out the embedded CodeSandbox demo:

You can also play with a demo with playback controls:

Try out Motion Path:

Try different types of Motion by changing the Animation Options:

I also created a complex demo page–with polyfills: https://okikio.github.io/native/demo/animate.html

You can find the source code for this demo on Github at: https://github.com/okikio/native/blob/master/build/ts/modules/animate.ts and https://github.com/okikio/native/blob/master/build/pug/animate.pug

The demo uses pug, and is a fairly complex setup, so, I highly suggest reading (https://github.com/okikio/native/tree/master/packages/animate#demo)

The native initiative uses Gitpod, so, if you want to play with the demo, I recommend clicking the Open in Gitpod link, since the entire environment is already setup for you, you don’t need to do any configuring. 

You can also check out some more complex examples at: https://codepen.io/collection/rxOEBO

For the most part, you can port your code from animejs to @okikio/animate with little to no issues.

But I should probably mention that @okikio/animate supports both the target and targets keywords for settings targets, @okikio/animate will merge both list of targets into one list and use Set’s to remove any repeated targets. @okikio/animate supports functions as animation options, so you can use staggering similar to animejs (Note: the order of arguments are different, read more in the Animation Options & CSS Properties as Methods section of the @okikio/animate readme).

Restrictions & Limitations

@okikio/animate isn’t perfect, nothing really is, and seeing as the Web Animation API is a living standard which is constantly being improved, @okikio/animate still has lots of space to grow, though I am constantly trying to improve it and would love your input, you can go to the Github repo open a new issue, create a pull request or we can have a discussion in Github Discussions.

The first limitation is that it doesn’t really have a timeline built-in, there are a couple reasons for this:

1. I ran out of time. I am still only a student, I don’t have lots of time to dedicate to developing all the projects I want to work on, and I simply just ran out of time.

2. I didn’t think a formal timeline was needed, as async/await programming was supported. Also, I added timelineOffset as an animation option, if anyone ever needs to create something similar to animejs’s timeline.

3. I wanted to make @okikio/animate as small as I could.

4. With GroupEffects and SequenceEffects coming soon, I thought it would be best to leave the package small until an actual need was present. Note: I highly suggest reading Daniel C. Wilson’s blog on the Web Animation API’s especially the 4th article in the series discussing GroupEffects and SequenceEffects (https://danielcwilson.com/blog/2015/09/animations-part-4/).

Another limitation on

@okikio/animate

is that it doesn’t support custom easing’s like spring, elastic, etc… but from what I can tell that’s already in development, read more on Jake Archibald’s Easing Worklet proposal (https://github.com/jakearchibald/easing-worklet). He discusses the multiple standards in discussion, I currently prefer his proposal, as it’s the easiest to implement and the most elegant. 

The last limitation was dealt with as of @okikio/[email protected], but there are still some limitations on CSS Properties that support color, check the Github release for more detail.

For example,


animate({ targets: [".div", document.querySelectorAll(".el")], // By default "px", will be applied translateX: 300, rotate: 120, left: 500, margin: "56 70 8em 70%", // No units will be auto applied color: "rgb(25, 25, 25)", "text-shadow": "25px 5px 15px rgb(25, 25, 25)"
});

Looking to the Future

As of right now some future features are just right around the corner, for example, the ScrollTimeline. I don’t think anyone actually knows when it’s getting released but since the ScrollTimeline works as of Chrome Canary 92, I think it’s safe to say it getting released fairly soon.

I built the timeline animation option into @okikio/animate to future proof it, you can check out an example here:

(Note: it may not work on your browser, you may need to use the Canary version of Chrome or turn on Experimental Web Platform features in Chrome Flags. From what I can tell it just works on Firefox, though, so…. 🤣).

I based my example off Bramus’s: https://codepen.io/bramus/pen/GRjPggQ

If you want to read more on the ScrollTimeline I would suggest reading Bramus’s article on it, he goes into it in depth (https://www.bram.us/2021/02/23/the-future-of-css-scroll-linked-animations-part-1/).

I would also suggest reading the Google Developers article on Animation Worklets (https://developers.google.com/web/updates/2018/10/animation-worklet).

Polyfills

The complex demo example above in the usage-examples-demos section, actually uses the polyfills required to support older browsers. You are going to need web-animations-next.min.js from web-animations-js, as in other to support timelines, and other modern features the KeyframeEffect constructor is required. 

For the polyfill, I use js to test if the KeyframeEffect was supported and if not to load the polyfill check out build/ts/webanimation-polyfill.ts in the Github repo, make sure to not add async/defer to the polyfill, or it will not work the way you expect, you should also polyfill Map, Set, and Promise.


<html> <head> <!-- Async --> <script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=default,es2015,es2018,Array.prototype.includes,Map,Set,Promise" async></script> <!-- NO Async/Defer --> <script src="./js/webanimation-polyfill.min.js"></script> </head> <body> <!-- Content --> </body>
</html>

When building for es6+ I highly recommend using esbuild for transpiling, bundling, and minifing. When building for es5, I suggest using esbuild (minify off), typescript (target of es5) & terser; as of now, this is the fastest setup for transpiling to es5, you can checkout the gulpfile from the demo for more details. 

Conclusion

@okikio/animate is a wrapper around the Web Animation API (WAAPI) that allows you to use all the features you love from animejs and other animation libraries, in a small and concise package.

Read more about it on npm or Github.

So, what are your thoughts on @okiko/animate, leave a comment on the dev.to article in the link below or join the discussion on Github Discussions.

Also published on dev.to at https://dev.to/okikio/okikio-animate-animejs-but-built-on-the-web-animation-api-nin

by Okiki Ojo @okikio. I am currently a student and part-time web dev, if you need a hand on any project, I would be happy to help.Read my stories

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.

Coinsmart. Beste Bitcoin-Börse in Europa
Source: https://hackernoon.com/introducing-the-web-animations-api-and-okikioanimate-qx4e35mx?source=rss

Continue Reading

Code

How To Implement Simple State Container From Scratch

Published

on

Let’s imagine that we have a component, a simple counter. The counter has a state and two buttons to manipulate with this state. We also have a function to render the state.

And here we have two problems:

  • representation layer and data layer are mixed. So, if you want to change one of them, you will touch both. It is a violation of SRP.
  • it is hard to support and maintain logic between components that have local states. Scalability problem arises.

To solve these problems we will use the FLUX approach which essentially means “Data downAction up”. Clicking any button will trigger action. So we have an action and now we need to change the state of our application. But how we suppose to do that? 

Redux is about functional programming, so we will use pure functions and immutability. Functions, that will change our state we will call reducer. It will get the current state and action as an argument and will return to the new state. The function will look like this:

function reducer(state, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; }
}

Now we need to create our store. Let’s right the new function and call it

createStore

.

function createStore(reducer) { let state = 0; return { getState(){ return state; }, dispatch(action){ state = reducer(state, action); } }
}

Before we can move on, it’s better to know what does observer pattern does. Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing. Let’s add this logic to our function:

function createStore(reducer) { let state = 0; const observers = []; return { getState(){ return state; }, subscribe(observer){ observers.push(observer); }, dispatch(action){ state = reducer(state, action); observers.forEach(cb => cb()); } }
}

And that’s it! We separate representation and data layer, move the state from component to separate place, dependencies now have on direction, data down and actions up.

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.

Coinsmart. Beste Bitcoin-Börse in Europa
Source: https://hackernoon.com/how-to-implement-simple-state-container-from-scratch-ry3035xl?source=rss

Continue Reading
Esports4 days ago

Lost Ark Founders Pack: Everything You Need to Know

Aviation4 days ago

Delta Air Lines Flight Diverts To Oklahoma Over Unruly Off-Duty Flight Attendant

Aviation3 days ago

Spirit Airlines Just Made The Best Argument For Lifting LaGuardia’s Perimeter Rule

Energy5 days ago

Daiki Axis Co., Ltd. (4245, First Section, Tokyo Stock Exchange) Overview of Operating Performance for the First Three Months Ended March 31, 2021

Esports2 days ago

Clash of Clans June 2021 Update patch notes

Esports4 days ago

Genshin Impact Murals: Location Guide

Blockchain3 days ago

Africa Leading Bitcoin P2P Trading Volume Growth in 2021

Esports2 days ago

Legends of Runeterra Patch 2.10.0 brings bug fixes and Pool Party cosmetics

Blockchain5 days ago

DCR Technical Analysis: Look for Support Levels of $130.13 and $126.01

Gaming3 days ago

Forza Horizon 5 Announced, Launches November 9

Cyber Security5 days ago

Cybersecurity Degrees in Colorado

Aviation2 days ago

Boeing 727 Set To Be Turned Into Luxury Hotel Experience

Esports4 days ago

Genshin Impact Music Rock Puzzle Guide

Blockchain5 days ago

Bitcoin Weekly Chart Appears to be in the Green Zone

Big Data2 days ago

In El Salvador’s bitcoin beach town, digital divide slows uptake

Blockchain2 days ago

Since It Adopted Bitcoin As Legal Tender, The World Is Looking At El Salvador

Blockchain4 days ago

Binance Is Launching a Decentralized NFT Platform

Blockchain4 days ago

Ripple price analysis: Ripple retests $0.80 support, prepares to push higher? 

HRTech2 days ago

Pre-Owned Luxury Car dealer Luxury Ride to add 80 Employees across functions to boost growth

Blockchain4 days ago

Kyber Network (KNC) Price Prediction 2021-2025: Will KNC Hit $4 by 2021?

Trending