Categories
JavaScript Tips

JavaScript Tips — Getting Keypresses, Callbacks to Promises and More

Spread the love

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Converting Existing Callbacks to Promises

There are a few ways to convert existing callbacks to promises.

One way is to use the Promise constructor.

For instance, we can write:

return new Promise((resolve, reject) => {  
  window.onload = resolve;  
});

We can put our callback code in the callback and then call resolve on it when it’s done running the code.

We can also use a library to do it.

jQuery has the Deferred property to let us do that:

$.Deferred((dfrd) => {  
   getData(id, dfrd.resolve, dfrd.reject);  
}).promise();

We call Deferred with a callback to returns a deferred object.

Then we call promise to return a promise.

We call resolve and reject in our async code like we do with the Promise constructor.

For Node style callbacks, we can also use the Promise constructor as we do before:

return new Promise((resolve, reject) => {  
  getStuff(param, (err, data) => {  
    if (err !== null) reject(err);  
    else resolve(data);  
  });  
});

We call reject when we encounter an error and resolve is we get data.

We can also use a library like Bluebird to convert Node-style callbacks to promises:

Promise.promisifyAll(asyncCode);

Promise is the Bluebird Promise object and it has the promisifyAll method to convert Node callbacks to promises.

Capture HTML Canvas as Image

We can capture HTML canvas as an image with the toDataURL method.

For instance, we can write:

const canvas = document.getElementById("mycanvas");  
const img = canvas.toDataURL("image/png");

We can use the img string directly as the value of the src attribute of the img tag.

Convert a Comma-Separated String to an Array

To convert a comma-separated string into an array, we can use the split method.

For instance, we can write:

const array = string.split(',');

If string is 'foo,baz'baz' , then we get ['foo', 'bar', 'baz'] as the value of array .

Static Variables in JavaScript

We can create a static variable in JavaScriopt by attaching them as properties of constructors.

For instance, we can write;

function Foo(){}  
Foo.bar = 'baz';

Then bar is a static property of the Foo constructor.

For classes, we can write:

class Foo {  
  static foo = 'bar'  
}

We use the static keyword to define the static foo property.

In either case, we can access it with Foo.bar .

Check that a Number is a Float or Integer

We can check if a floating point number is an integer with the remainder operator.

We write:

n % 1 === 0;

to do that, where n is a number.

If it can be evenly divisible by 1, then we know it’s an integer.

We can also use the Number.isSafeInteger method to check.

And there’s also a Number.isInteger method.

They both take a number that we want to check:

`Number.isInteger(1);  
Number.`isSafeInteger`(1);`

Obfuscate JavaScript

To obfuscate JavaScript,m we can use the Uglify JS package to do it.

We can install it by running:

npm install -g uglify-js

Uglified code can be reversed.

Also, private strings can still be visible after they’re uglified,.

window.onload vs document.onload

There is a difference between window.onload and document.onload .

window.onload is run when the entire page loads, which includes images, CSS, scripts, etc,.

document.onload is called when the DOM is ready, which can be prior to images and other external resources are loaded.

Get Which Key was Pressed with jQuery Event Keypress

We can get the key that’s pressed with the keyCode or which properties.

To check if the enter key is pressed, we check for code 13:

const code = e.keyCode || e.which;  
if (code === 13) {   
  //...  
}

Self-References in Object Literals

We can use a getter to return data that are derived from other properties in the object.

For instance, we can write:

const foo = {  
  a: 5,  
  b: 6,  
  get sum() {  
    return this.a + this.b;  
  }  
}

We have the sum getter which is derived from adding a and b together.

Since getters are methods, we can use this inside it.

Conclusion

There many ways to convert callbacks to promises.

We can use getters to create properties that are derived from other properties.

JavaScript constructors can have static variables.

We can get the key that’s pressed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *