JavaScript – muhammad.dev https://muhammad.dev WordPress, React, and Remote Work Thu, 17 Aug 2017 11:38:57 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://i0.wp.com/muhammad.dev/wp-content/uploads/2021/09/cropped-favicon.jpeg?fit=32%2C32&ssl=1 JavaScript – muhammad.dev https://muhammad.dev 32 32 183256168 Building a Calculator with Vue.js and Flexbox https://muhammad.dev/building-calculator-vue-js-flexbox/ https://muhammad.dev/building-calculator-vue-js-flexbox/#respond Thu, 17 Aug 2017 11:38:57 +0000 https://mtwoblog.com/?p=555 Vue.js is one of the leading JavaScript libraries out there, which is easy to get started and very scalable at the same time. Similarly, CSS3 Flexbox is a relatively new feature that makes our design process simpler. This is a tutorial on creating a simple calculator using Vue.js CLI and CSS3 Flexbox. This post first appeared on Laccadive IO Blog.


Getting Started

To get started with the Vue.js CLI, we have to first install the NPM package globally.

$ npm install -g vue-cli

Next, we have to move to a specific directory, where we want to create the project and perform an initialization:

$ vue init webpack vue-calc

where ‘webpack’ is the template name and ‘vue-calc’ is the name of our project.

This will prompt you for more details to create the project. Like this:

Vue CLI
Vue CLI

Next you need to perform the three suggested commands:

$ cd vue-calc
$ npm install
$ npm run dev

This will move into the project directory, install the relevant packages, run a node development server on port:8080 and open up the browser to load the following.

Vue.js Initial
Vue.js Initial

Now comes the interesting part.

The Project Directory

Vue.js works using components, similar to React. Our code will therefore be inside the ‘components’ folder:

Project Structure
Project Structure

Create a new file inside the components folder and and name it ‘Calculator.vue’.

Vue.js code

There are multiple ways to write code in Vue, one is to write it within script tags. Another way is to write it in a component style, which we are doing in this example.

In a component, we have three main elements:
1. <template> – this is where our HTML is written
2. <script> – the JS code goes here
3. <style> – the CSS goes here

The following gist contains the code that will go into Calculator.js: Get the code!

Copy the whole page and paste it inside Calculator.js.

Now we have to give a reference to Calculator.vue from App.vue. Open App.vue and replace the following inside the script tags:

import Calculator from './components/Calculator'

export default {
 name: 'app',
 components: {
 Calculator
 }
}

The following are some pointers for each of the three sections of code:

Template

  • Whatever is entered {{ withinDoubleCurlyBraces }} will be taken from script -> data() or from a function inside script -> methods:
  • @click is the same as v-on:click, which is an event to be fired on clicking the element
  • enterNum(‘7’) and enterSign(‘+’) are methods which enters a number and sign respectively

Script

  • Whatever is given as ‘name‘ will be the name of the component
  • data () contains the JS variables used within the component
  • methods: contain all of the methods used in the component

Style

scoped‘ means these styles apply to elements within this component only. This is pretty cool since we don’t have to worry about repeating a class in another component. The following are some CSS Flexbox-specific styles used.

.buttons{ /* for the buton container */ 
 display: flex;
 flex-wrap: wrap;
 padding: 10px;
}

.buttons button { /* for each button */
 flex-grow: 1;
}

.one { /* contains the DEL and C buttons*/
 display: flex;
 flex-grow: 1;
}

Summing up

That’s all folks. Hope you realized how simple it is to get started with Vue.js. In case you would like the full project, please visit the Github Link and feel free to fork the project to improve it further.

]]>
https://muhammad.dev/building-calculator-vue-js-flexbox/feed/ 0 555
JavaScript Promises – a meetup and an example https://muhammad.dev/javascript-promises-meetup-example/ https://muhammad.dev/javascript-promises-meetup-example/#respond Tue, 01 Nov 2016 12:41:31 +0000 https://mtwoblog.com/?p=460 The Colombo JavaScript Meetup group organised an event titled ‘JavaScript Promises’ on 20 October, 2016 at WSO2, Colombo 3.

JavaScript Promises

The two speakers – Isuru and Raathigeshan were both from Zone 24×7. Below are some of the notes I took from the two talks.

The old school way

Synchronous programming is when the code runs statement by statement, only running the following statement when the current one is completed.

Isuru began the talk introducing the Synchronous (old school) way of coding – when receiving data from an API endpoint for example. The solution was to google and go to stackoverflow only to come back and write a setTimeout().

The problem with this approach is that when the synchronous function is huge, this would freeze the application.

The (traditional) Asynchronous way

Asynchronous JavaScript essentially is when a code is not blocked by something that is to be completed. The page can load and wait for whatever is to be received – maybe some data through an API call. After the return is successful, a callback is made which would typically build the HTML based on the returned data.

Yes, you have achieved non blocking calls. Awesome!

Or is it? While this does ensure an async way of doing things, this way also has a couple of drawbacks:

  • Callback Hell – when chaining an absurd number of callback functions. After some time, the code would grow more horizontally than vertically  – and that is not a good thing. This problem is also known as The Pyramid of Doom 🙂
  • The stack/return could be lost, which could throw errors
  • The callback may execute multiple times

Enter Promises

The purpose of this blog post is not to lecture you on Promises. There are other awesome ways you can learn about it- like this one.

However, two things make promises useful and different from event listeners:

  • A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.
  • If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier.

An example with Promises

The code below is a simple representation of how Promises can be implemented without any libraries since the current browsers already have support for it.

This works on Google Chrome 54, Mozilla Firefox 49 and Microsoft Edge 38.

results

fetch() is a method which is natively supported in modern browsers. It allows us to fetch data from API endpoints (duh).

The then() method is called with a promise and it takes two optional arguments – a success callback and a failure callback.

The catch() block is used to handle errors as you might have guessed it already.

Promises allow chaining – to link one then method to another – the return from the previous is the argument for the next – which is a way to condense our code. Combine this with ES6 Arrow functions and we have a lot done in a few lines of code.

baconipsum.com has a JSON API REST interface for generating meaty lorem ipsum text and can be used by any application. It returns a JSON string array of paragraphs and can be accessed via https.

In the above example, the fetch method receives the result as a response object,

  • then converts it into an JSON object – which contains a single array,
  • then into a string – which contains a long string of sentences separated by a period,
  • then splits the string into an array where there are periods
  • then prints each item in that array as a list item

You can notice that the promise gives us a clean way to code subsequent steps – in a story-telling fashion.

The future – async/await

Lastly, the speakers touched on this new way to do what we did in promises. Added in ES7 (ES2016), it is supposed to give us the benefits of synchronous programming when writing code in an asynchronous way, such as the ability to use try/catch. It is supported by Babel and Chrome 55.

I have to understand it myself properly to explain further. I hope to try this once I fully understand promises.

Conclusion

In short, the meetup was indeed useful as #CMBJS meetups usually are – in reigniting our love for JS. This was a blog post I promised myself 12 days ago.

]]>
https://muhammad.dev/javascript-promises-meetup-example/feed/ 0 460