SlideShare a Scribd company logo
Create a Meteor chat app in 30 minutes
In the previous post, we’ve discovered the very basic of Meteor (https://blog.designveloper.com/2016/06/11/get-started-with-meteor/). Now let’s create something interesting like this:
J A V A S C R I P T ( H T T P S : / / B L O G . D E S I G N V E L O P E R . C O M / C A T E G O R Y / J A V A S C R I P T / ) , M E T E O R ( H T T P S : / / B L O G . D E S I G N V E L O P E R . C O M / C A T E G O R Y / M E T E O R / ) , P R O G R A M M I N G L A N G U A G E
( H T T P S : / / B L O G . D E S I G N V E L O P E R . C O M / C A T E G O R Y / P R O G R A M M I N G - L A N G U A G E / )
B y L i n h Vu ( h t t p s : // b l o g . d e s i g n v e l o p e r. c o m / a u t h o r / l i n h v n / ) o n J u n e 1 3 , 2 0 1 6
It’s a simple real-time chat, with many users. Follow these steps and you’ll nish it in just 30 minutes!
W h ere do I b egin ?
To create a Meteor app, simply open your terminal and run this command:
meteor create simple-chat
Now try to run your rst Meteor app:
cd simple-chat
meteor
Let’s check it out using your web browser: http://localhost:3000/ (http://localhost:3000/)
You ’ve told t h at it ’s all J avaS crip t , wh y does it look s o s t ran ge?
Every new Meteor app includes Blaze, which is Meteor’s built-in reactive rendering library. Usually, templates are written in Spacebars. These templates are compiled into JavaScript UI components that are rendered by the
Blaze library. I’ll continue to explain it later
Now add some folders like this:
This is the le structure that Meteor recommends us. You can nd out more here (http://guide.meteor.com/structure.html#javascript-structure).
Next, open client/main.html, replace all the code with this:
<head>
<title>My Simple Chat</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
We will write the body code in a new le. Let’s add some les to the imports/ui directory:
body.html
<body>
<h3>SIMPLE METEOR CHAT</h3>
<ul>
     {{#each messages}}
       {{> message}}
     {{/each}}
</ul>
</body>
<template name="message">
 <li>{{text}}</li>
</template>
and body.js
import { Template } from 'meteor/templating';
import './body.html';
Template.body.helpers({
 messages: [
   { text: 'Hello,' },
   { text: 'Nice to meet you!' },
   { text: '<3' },
 ],
});
Also open le client/main.js and replace all the codes with this:
import '../imports/ui/body.js';
Then you will see something like this:
You can see that Meteor renders the HTML with head section from <head> tag in main.html, body section from <body> tag in body.html. Look at the body, you will see this:
{{#each messages}}
       {{> message}}
{{/each}}
This is Spacebar syntax. Like I’ve explained before, Spacebar is a Meteor template language. It uses statements surrounded by double curly braces such as {{#each}} and {{#if}} to let you add logic and data to your
views. (You can read more about Blaze (http://guide.meteor.com/blaze.html) and Spacebar (http://meteorcapture.com/spacebars/)).
So in the code above, each item from the messages collection will be put into template named message. Template in Meteor is just like Partial view in ASP.NET, it’s a chunk of HTML that can be safely inserted into an existing
DOM. You can de ne it using this:
<template name="templateName">
#put template code here
</template>
and reference in your JavaScript with Template.templateName . Furthermore, in your JavaScript, the body section can be referenced with Template.body . It’s a special “parent” template including the other child templates.
Now we have 3 messages, created by the Template.body.helpers in the body.js. So how can we can type message, send it and show in our app? We will gure out how to do it later.
C an we s t y le it ?
The easiest way is using Bootstrap. With Meteor, adding Bootstrap can be done in the blink of an eye. Open another terminal tab, go to the simple-chat directory and run this:
meteor add twbs:bootstrap
Done! Now we can use Bootstrap. Replace your body.html code with this:
<body>
 <div class="container">
   <div class="row">
     <h3 class="text-center" >SIMPLE METEOR CHAT</h3>
<!-- text holder -->
     <div class="col-md-12">
<!-- login button -->
       <div class="panel panel-info">
         <div class="panel-heading">
           GROUP CHAT
         </div>
         <div class="panel-body">
           <ul class="media-list">
             <!-- message template -->
             {{#each messages}}
               {{> message}}
             {{/each}}
           </ul>
         </div>
         <!-- message textbox -->
         <form class="new-message">
           <div class="panel-footer">
             <div class="input-group">
               <input type="text" name="text" class="form-control" placeholder="Enter Message" />
               <span class="input-group-btn">
                 <button class="btn btn-info send" type="submit">SEND</button>
               </span>
             </div>
           </div>
         </form>
       </div>
     </div>
   </div>
 </div>
</body>
Then we will create several les in the imports/ui/ directory to separate each template to a different html le and js le.
Create new le message.html:
<template name="message">
 <li class="media">
   <div class="media-body">
     <div class="media">
       <a class="pull-left" href="#">
       <img class="media-object img-circle img-responsive" src="https://lorempixel.com/60/60/people/" />
       </a>
       <div class="media-body" >
         {{text}}
       </div>
     </div>
   </div>
 </li>
</template>
Create new le message.js:
import { Template } from 'meteor/templating';
import './message.html';
Open body.js and add this after import './body.html' :
import './message.js';
Thank to Bootstrap we have such an elegant app:
N ice, b u t it does n’t work, I can’t s en d mes s age! W h y oh wh y ?
Don’t be too hurry! :-p . Now we will create a database collection to store the messages. Create a new le messages.js in the imports/api/ directory like this:
import { Mongo } from 'meteor/mongo';
export const Messages = new Mongo.Collection('messages');
In MongoDB, this is how we create a collection in JavaScript:
MyCollection = new Mongo.Collection("my-collection")
On the server, this sets up a MongoDB collection called my-collection; on the client, this creates a cache connected to the server collection. In this demo, to make it easy, assume that the entire database is present on the
client.
We also import the messages.js to the server. Open the server/main.js and add this to the second line:
import '../imports/api/messages.js';
Now we can display message from the collection by opening body.js and replacing the Template.body.helpers with this:
import { Messages } from '../api/messages.js';
Template.body.helpers({
 tasks() {
   return Tasks.find();
 },
});
Don’t worry when your chat group is empty. Just a few steps left then you will receive your messages.
As we created the message textbox in the body.html in the previous step, now we will handle the submit event to insert new message. Add this to the end of the body.js:
Template.body.events({
 'submit .new-message'(event) {
   // Prevent default browser form submit
   event.preventDefault();
   // Get value from form element
   const target = event.target;
   const text = target.text.value;
   // Insert a message into the collection
   Messages.insert({
     text,
     createdAt: new Date(), // current time
//user information
   });
   // Clear form
   target.text.value = '';
   // scroll to last message
   $('.panel-body').scrollTop($('.media-list').height())
},
});
Now you can say Hello world!
You can open another browser window and chat to yourself to see if it works real-time. Awesome, right?
Th is is n ot a ch at . Ever yon e mu s t h ave t h eir own accou n t s an d log in , righ t ?
It’s simple man. If you think we have a lot of things to deal with, then you will be surprised. Just run this command:
meteor add accounts-ui accounts-password
This will enable Meteor accounts system and a drop-in login user interface with multi-user functionality.
Then open body.html and replace the <!-- text holder --> with this:
<h5 class="text-center text-muted">Sign in to join!</h5>
and replace the <!-- login button --> with this:
{{> loginButtons}}
And add this before and after the <form> tag:
{{#if currentUser}}
<form…>
…
</form>
{{/if}}
Then we will add a new le accounts-con g.js in the imports/startup/ directory to make easier to sign up:
import { Accounts } from 'meteor/accounts-base';
Accounts.ui.config({
 passwordSignupFields: 'USERNAME_ONLY',
});
And import it by opening client/main.js and inserting this to the rst line:
import '../imports/startup/accounts-config.js';
Then you will see our app now looks like this:
You can simply create account, sign in… To join our chat!
Let’s add some more elds to your messages collection to see who sends it. Open the body.js and replace //user information inside the function Messages.insert with this:
owner: Meteor.userId(), username:Meteor.user().username,
And open the message.html, replace the <!-- user information --> with this:
<small class="text-muted"><strong>{{username}}</strong> | {{createdAt}}</small>
Finally, add this to client/main.css:
.panel-body{
 overflow-y:scroll;
 height:60vh;
}
All done! Enjoy your Meteor chat app!
C on clu s ion
Through this simple app, we’ve discovered something more about Meteor:
File structure in Meteor
Blaze – Meteor’s default frontend rendering system
Spacebar – Meteor’s template language
How to add packages to your Meteor app
Hope you nd it useful. Keep practising everyday!
P.s : You can get the all code here (https://github.com/31131021883/simple-chat/).
(https://www.facebook.com/sharer/sharer.php?
u=https%3A%2F%2Fblog.designveloper.com%2F2016%2F06%2F13%2Fcreate-
a-
meteor-
chat-
app-in-
30-
minutes%2F)
(http://twitter.com/intent/tweet?
source=Designveloper
Software
agency
-
Meteor
prime
partner&text=https%3A%2F%2Fblog.designveloper.com%2F2016%2F06%2F13%2Fcreate-
a-
meteor-
chat-
app-in-
30-
minutes%2F)
(https://plus.google.com/share?
url=https%3A%2F%2Fblog.designveloper.com%2F2016%2F06%2F13%2Fcreate-
a-
meteor-
chat-
app-in-
30-
minutes%2F)
(http://www.linkedin.com/shareArticle?
mini=true&url=https%3A%2F%2Fblog.designveloper.com%2F2016%2F06%2F13%2Fcreate-
a-
meteor-
chat-
app-in-
30-
minutes%2F&title=Create%20a%20Meteor%20chat%20app%20in%2030%20minutes&summary=In%20the%20previous%20post%2C%20we%26%23821
time%20chat%2C%20with%20many%20users.%20Follow%20these%20steps%20and%20you%26%238217%3Bll%20 nish%20it%20in%20just%2030%20m
Software
agency
-
Meteor
prime
partner)
(http://www.tumblr.com/share/link?
url=https%3A%2F%2Fblog.designveloper.com%2F2016%2F06%2F13%2Fcreate-
a-
meteor-
chat-
app-in-
30-
minutes%2F&name=Create%20a%20Meteor%20chat%20app%20in%2030%20minutes&description=In%20the%20previous%20post%2C%20w
time%20chat%2C%20with%20many%20users.%20Follow%20these%20steps%20and%20you%26%238217%3Bll%20 nish%20it%20in%20just%
Chat app JavaScript Meteor Real-time
Get started with Meteor (https://blog.designveloper.com/2016/06/11/get-started-with-meteor/)

More Related Content

What's hot

Intro to WebSockets (in Java)
Intro to WebSockets (in Java)Intro to WebSockets (in Java)
Intro to WebSockets (in Java)osintegrators
 
New Component Patterns in Ember.js
New Component Patterns in Ember.jsNew Component Patterns in Ember.js
New Component Patterns in Ember.jsMatthew Beale
 
Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8Katy Slemon
 
Meteor presentation
Meteor presentationMeteor presentation
Meteor presentationscandiweb
 
4007655 introduction-to-javascript
4007655 introduction-to-javascript4007655 introduction-to-javascript
4007655 introduction-to-javascriptVikash Chandra
 
Instant and offline apps with Service Worker
Instant and offline apps with Service WorkerInstant and offline apps with Service Worker
Instant and offline apps with Service WorkerChang W. Doh
 
Spring Boot & WebSocket
Spring Boot & WebSocketSpring Boot & WebSocket
Spring Boot & WebSocketMing-Ying Wu
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JSEueung Mulyana
 
Flutter hooks tutorial (part 1) flutter animation using hooks (use effect and...
Flutter hooks tutorial (part 1) flutter animation using hooks (use effect and...Flutter hooks tutorial (part 1) flutter animation using hooks (use effect and...
Flutter hooks tutorial (part 1) flutter animation using hooks (use effect and...Katy Slemon
 
Installing php 7.4 Nginx Laravel 7.x on Centos 8
Installing php 7.4 Nginx Laravel 7.x on Centos 8Installing php 7.4 Nginx Laravel 7.x on Centos 8
Installing php 7.4 Nginx Laravel 7.x on Centos 8Raja Rozali Raja Hasan
 
Service Worker 201 (en)
Service Worker 201 (en)Service Worker 201 (en)
Service Worker 201 (en)Chang W. Doh
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioKaty Slemon
 
Einführung in Angular 2
Einführung in Angular 2Einführung in Angular 2
Einführung in Angular 2Johannes Hoppe
 
Don't Over-React - just use Vue!
Don't Over-React - just use Vue!Don't Over-React - just use Vue!
Don't Over-React - just use Vue!Raymond Camden
 
OpenWhisk Lab
OpenWhisk Lab OpenWhisk Lab
OpenWhisk Lab Dev_Events
 
Best Laravel Eloquent Tips and Tricks
Best Laravel Eloquent Tips and TricksBest Laravel Eloquent Tips and Tricks
Best Laravel Eloquent Tips and TricksTechtic Solutions
 
10 ways to bind multiple models on a view in mvc code project
10 ways to bind multiple models on a view in mvc   code project10 ways to bind multiple models on a view in mvc   code project
10 ways to bind multiple models on a view in mvc code projectAkshat Kumar
 

What's hot (20)

Intro to WebSockets (in Java)
Intro to WebSockets (in Java)Intro to WebSockets (in Java)
Intro to WebSockets (in Java)
 
New Component Patterns in Ember.js
New Component Patterns in Ember.jsNew Component Patterns in Ember.js
New Component Patterns in Ember.js
 
Meteor
MeteorMeteor
Meteor
 
Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8
 
Meteor presentation
Meteor presentationMeteor presentation
Meteor presentation
 
Android how to hellowidget
Android how to hellowidgetAndroid how to hellowidget
Android how to hellowidget
 
4007655 introduction-to-javascript
4007655 introduction-to-javascript4007655 introduction-to-javascript
4007655 introduction-to-javascript
 
Instant and offline apps with Service Worker
Instant and offline apps with Service WorkerInstant and offline apps with Service Worker
Instant and offline apps with Service Worker
 
Spring Boot & WebSocket
Spring Boot & WebSocketSpring Boot & WebSocket
Spring Boot & WebSocket
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JS
 
Flutter hooks tutorial (part 1) flutter animation using hooks (use effect and...
Flutter hooks tutorial (part 1) flutter animation using hooks (use effect and...Flutter hooks tutorial (part 1) flutter animation using hooks (use effect and...
Flutter hooks tutorial (part 1) flutter animation using hooks (use effect and...
 
Installing php 7.4 Nginx Laravel 7.x on Centos 8
Installing php 7.4 Nginx Laravel 7.x on Centos 8Installing php 7.4 Nginx Laravel 7.x on Centos 8
Installing php 7.4 Nginx Laravel 7.x on Centos 8
 
Service Worker 201 (en)
Service Worker 201 (en)Service Worker 201 (en)
Service Worker 201 (en)
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
Einführung in Angular 2
Einführung in Angular 2Einführung in Angular 2
Einführung in Angular 2
 
Don't Over-React - just use Vue!
Don't Over-React - just use Vue!Don't Over-React - just use Vue!
Don't Over-React - just use Vue!
 
OpenWhisk Lab
OpenWhisk Lab OpenWhisk Lab
OpenWhisk Lab
 
React render props
React render propsReact render props
React render props
 
Best Laravel Eloquent Tips and Tricks
Best Laravel Eloquent Tips and TricksBest Laravel Eloquent Tips and Tricks
Best Laravel Eloquent Tips and Tricks
 
10 ways to bind multiple models on a view in mvc code project
10 ways to bind multiple models on a view in mvc   code project10 ways to bind multiple models on a view in mvc   code project
10 ways to bind multiple models on a view in mvc code project
 

Similar to Create a meteor chat app in 30 minutes

130297267 transformations
130297267 transformations130297267 transformations
130297267 transformationsSunil Pandey
 
How to deploy and scale your meteor apps
How to deploy and scale your meteor appsHow to deploy and scale your meteor apps
How to deploy and scale your meteor appsDesignveloper
 
1 Web Page Foundations Overview This lab walk.docx
1  Web Page Foundations Overview This lab walk.docx1  Web Page Foundations Overview This lab walk.docx
1 Web Page Foundations Overview This lab walk.docxhoney725342
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchKaty Slemon
 
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 MinutesBuild Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 MinutesRobert Li
 
Meteor.js Workshop by Dopravo
Meteor.js Workshop by DopravoMeteor.js Workshop by Dopravo
Meteor.js Workshop by DopravoArabNet ME
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialKaty Slemon
 
Introduction to Mangento
Introduction to Mangento Introduction to Mangento
Introduction to Mangento Ravi Mehrotra
 
Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18Thinkful
 
Dive into SObjectizer 5.5. Introductory part
Dive into SObjectizer 5.5. Introductory partDive into SObjectizer 5.5. Introductory part
Dive into SObjectizer 5.5. Introductory partYauheni Akhotnikau
 
Micro services from scratch - Part 1
Micro services from scratch - Part 1Micro services from scratch - Part 1
Micro services from scratch - Part 1Azrul MADISA
 
MoodLocator HwT
MoodLocator HwTMoodLocator HwT
MoodLocator HwTJDihlmann
 
Using prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesUsing prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesDavid Voyles
 

Similar to Create a meteor chat app in 30 minutes (20)

130297267 transformations
130297267 transformations130297267 transformations
130297267 transformations
 
How to deploy and scale your meteor apps
How to deploy and scale your meteor appsHow to deploy and scale your meteor apps
How to deploy and scale your meteor apps
 
forms
formsforms
forms
 
forms
formsforms
forms
 
1 Web Page Foundations Overview This lab walk.docx
1  Web Page Foundations Overview This lab walk.docx1  Web Page Foundations Overview This lab walk.docx
1 Web Page Foundations Overview This lab walk.docx
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
 
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 MinutesBuild Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
 
Meteor.js Workshop by Dopravo
Meteor.js Workshop by DopravoMeteor.js Workshop by Dopravo
Meteor.js Workshop by Dopravo
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorial
 
Introduction to Mangento
Introduction to Mangento Introduction to Mangento
Introduction to Mangento
 
Mangento
MangentoMangento
Mangento
 
Create Components in TomatoCMS
Create Components in TomatoCMSCreate Components in TomatoCMS
Create Components in TomatoCMS
 
Meteor
MeteorMeteor
Meteor
 
Ph
PhPh
Ph
 
Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
Dive into SObjectizer 5.5. Introductory part
Dive into SObjectizer 5.5. Introductory partDive into SObjectizer 5.5. Introductory part
Dive into SObjectizer 5.5. Introductory part
 
Micro services from scratch - Part 1
Micro services from scratch - Part 1Micro services from scratch - Part 1
Micro services from scratch - Part 1
 
MoodLocator HwT
MoodLocator HwTMoodLocator HwT
MoodLocator HwT
 
Using prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesUsing prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile services
 

More from Designveloper

Let us take care of your brand image
Let us take care of your brand imageLet us take care of your brand image
Let us take care of your brand imageDesignveloper
 
5 java script frameworks to watch in 2017
5 java script frameworks to watch in 20175 java script frameworks to watch in 2017
5 java script frameworks to watch in 2017Designveloper
 
Happy international women's day!
Happy international women's day!Happy international women's day!
Happy international women's day!Designveloper
 
Typing racer game - a nice break from work
Typing racer game  - a nice break from workTyping racer game  - a nice break from work
Typing racer game - a nice break from workDesignveloper
 
Should we work remotely?
Should we work remotely?Should we work remotely?
Should we work remotely?Designveloper
 
Meet song nhi your virtual financial assistance
Meet song nhi   your virtual financial assistanceMeet song nhi   your virtual financial assistance
Meet song nhi your virtual financial assistanceDesignveloper
 
Why pair programming is a good idea
Why pair programming is a good idea Why pair programming is a good idea
Why pair programming is a good idea Designveloper
 
5 worst mistakes of diy websites
5 worst mistakes of diy websites5 worst mistakes of diy websites
5 worst mistakes of diy websitesDesignveloper
 
Basic glossary of web design terms for non designers (part 2)
Basic glossary of web design terms for non designers (part 2)Basic glossary of web design terms for non designers (part 2)
Basic glossary of web design terms for non designers (part 2)Designveloper
 
Single page web application development using meteor js
Single page web application development using meteor jsSingle page web application development using meteor js
Single page web application development using meteor jsDesignveloper
 
Multiplayer game with unity3 d and meteor
Multiplayer game with unity3 d and meteorMultiplayer game with unity3 d and meteor
Multiplayer game with unity3 d and meteorDesignveloper
 
Awesome free resources for learning javascript
Awesome free resources for learning javascriptAwesome free resources for learning javascript
Awesome free resources for learning javascriptDesignveloper
 
What is the best java script frameworks to learn?
What is the best java script frameworks to learn?What is the best java script frameworks to learn?
What is the best java script frameworks to learn?Designveloper
 
Travelling forms a young man
Travelling forms a young manTravelling forms a young man
Travelling forms a young manDesignveloper
 
5 compelling reasons your website should be responsive
5 compelling reasons your website should be responsive5 compelling reasons your website should be responsive
5 compelling reasons your website should be responsiveDesignveloper
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with trackerDesignveloper
 
Benefits of using single page websites
Benefits of using single page websitesBenefits of using single page websites
Benefits of using single page websitesDesignveloper
 
What is the best programming language for beginner?
What is the best programming language for beginner?What is the best programming language for beginner?
What is the best programming language for beginner?Designveloper
 
No sql injection in meteor.js application
No sql injection in meteor.js applicationNo sql injection in meteor.js application
No sql injection in meteor.js applicationDesignveloper
 
Meetup groups you need to join if you are new to tech
Meetup groups you need to join if you are new to techMeetup groups you need to join if you are new to tech
Meetup groups you need to join if you are new to techDesignveloper
 

More from Designveloper (20)

Let us take care of your brand image
Let us take care of your brand imageLet us take care of your brand image
Let us take care of your brand image
 
5 java script frameworks to watch in 2017
5 java script frameworks to watch in 20175 java script frameworks to watch in 2017
5 java script frameworks to watch in 2017
 
Happy international women's day!
Happy international women's day!Happy international women's day!
Happy international women's day!
 
Typing racer game - a nice break from work
Typing racer game  - a nice break from workTyping racer game  - a nice break from work
Typing racer game - a nice break from work
 
Should we work remotely?
Should we work remotely?Should we work remotely?
Should we work remotely?
 
Meet song nhi your virtual financial assistance
Meet song nhi   your virtual financial assistanceMeet song nhi   your virtual financial assistance
Meet song nhi your virtual financial assistance
 
Why pair programming is a good idea
Why pair programming is a good idea Why pair programming is a good idea
Why pair programming is a good idea
 
5 worst mistakes of diy websites
5 worst mistakes of diy websites5 worst mistakes of diy websites
5 worst mistakes of diy websites
 
Basic glossary of web design terms for non designers (part 2)
Basic glossary of web design terms for non designers (part 2)Basic glossary of web design terms for non designers (part 2)
Basic glossary of web design terms for non designers (part 2)
 
Single page web application development using meteor js
Single page web application development using meteor jsSingle page web application development using meteor js
Single page web application development using meteor js
 
Multiplayer game with unity3 d and meteor
Multiplayer game with unity3 d and meteorMultiplayer game with unity3 d and meteor
Multiplayer game with unity3 d and meteor
 
Awesome free resources for learning javascript
Awesome free resources for learning javascriptAwesome free resources for learning javascript
Awesome free resources for learning javascript
 
What is the best java script frameworks to learn?
What is the best java script frameworks to learn?What is the best java script frameworks to learn?
What is the best java script frameworks to learn?
 
Travelling forms a young man
Travelling forms a young manTravelling forms a young man
Travelling forms a young man
 
5 compelling reasons your website should be responsive
5 compelling reasons your website should be responsive5 compelling reasons your website should be responsive
5 compelling reasons your website should be responsive
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
 
Benefits of using single page websites
Benefits of using single page websitesBenefits of using single page websites
Benefits of using single page websites
 
What is the best programming language for beginner?
What is the best programming language for beginner?What is the best programming language for beginner?
What is the best programming language for beginner?
 
No sql injection in meteor.js application
No sql injection in meteor.js applicationNo sql injection in meteor.js application
No sql injection in meteor.js application
 
Meetup groups you need to join if you are new to tech
Meetup groups you need to join if you are new to techMeetup groups you need to join if you are new to tech
Meetup groups you need to join if you are new to tech
 

Recently uploaded

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backElena Simperl
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsExpeed Software
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIES VE
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfalexjohnson7307
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...CzechDreamin
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024Stephanie Beckett
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka DoktorováCzechDreamin
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaRTTS
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...Product School
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 

Recently uploaded (20)

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdf
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 

Create a meteor chat app in 30 minutes

  • 1. Create a Meteor chat app in 30 minutes In the previous post, we’ve discovered the very basic of Meteor (https://blog.designveloper.com/2016/06/11/get-started-with-meteor/). Now let’s create something interesting like this: J A V A S C R I P T ( H T T P S : / / B L O G . D E S I G N V E L O P E R . C O M / C A T E G O R Y / J A V A S C R I P T / ) , M E T E O R ( H T T P S : / / B L O G . D E S I G N V E L O P E R . C O M / C A T E G O R Y / M E T E O R / ) , P R O G R A M M I N G L A N G U A G E ( H T T P S : / / B L O G . D E S I G N V E L O P E R . C O M / C A T E G O R Y / P R O G R A M M I N G - L A N G U A G E / ) B y L i n h Vu ( h t t p s : // b l o g . d e s i g n v e l o p e r. c o m / a u t h o r / l i n h v n / ) o n J u n e 1 3 , 2 0 1 6
  • 2. It’s a simple real-time chat, with many users. Follow these steps and you’ll nish it in just 30 minutes! W h ere do I b egin ? To create a Meteor app, simply open your terminal and run this command: meteor create simple-chat Now try to run your rst Meteor app: cd simple-chat meteor Let’s check it out using your web browser: http://localhost:3000/ (http://localhost:3000/) You ’ve told t h at it ’s all J avaS crip t , wh y does it look s o s t ran ge? Every new Meteor app includes Blaze, which is Meteor’s built-in reactive rendering library. Usually, templates are written in Spacebars. These templates are compiled into JavaScript UI components that are rendered by the Blaze library. I’ll continue to explain it later
  • 3. Now add some folders like this: This is the le structure that Meteor recommends us. You can nd out more here (http://guide.meteor.com/structure.html#javascript-structure). Next, open client/main.html, replace all the code with this: <head> <title>My Simple Chat</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> </head> We will write the body code in a new le. Let’s add some les to the imports/ui directory: body.html <body> <h3>SIMPLE METEOR CHAT</h3> <ul>      {{#each messages}}        {{> message}}      {{/each}} </ul> </body> <template name="message">  <li>{{text}}</li> </template> and body.js import { Template } from 'meteor/templating'; import './body.html'; Template.body.helpers({  messages: [    { text: 'Hello,' },    { text: 'Nice to meet you!' },    { text: '<3' },  ], }); Also open le client/main.js and replace all the codes with this:
  • 4. import '../imports/ui/body.js'; Then you will see something like this: You can see that Meteor renders the HTML with head section from <head> tag in main.html, body section from <body> tag in body.html. Look at the body, you will see this: {{#each messages}}        {{> message}} {{/each}} This is Spacebar syntax. Like I’ve explained before, Spacebar is a Meteor template language. It uses statements surrounded by double curly braces such as {{#each}} and {{#if}} to let you add logic and data to your views. (You can read more about Blaze (http://guide.meteor.com/blaze.html) and Spacebar (http://meteorcapture.com/spacebars/)). So in the code above, each item from the messages collection will be put into template named message. Template in Meteor is just like Partial view in ASP.NET, it’s a chunk of HTML that can be safely inserted into an existing DOM. You can de ne it using this: <template name="templateName"> #put template code here </template> and reference in your JavaScript with Template.templateName . Furthermore, in your JavaScript, the body section can be referenced with Template.body . It’s a special “parent” template including the other child templates. Now we have 3 messages, created by the Template.body.helpers in the body.js. So how can we can type message, send it and show in our app? We will gure out how to do it later. C an we s t y le it ? The easiest way is using Bootstrap. With Meteor, adding Bootstrap can be done in the blink of an eye. Open another terminal tab, go to the simple-chat directory and run this: meteor add twbs:bootstrap Done! Now we can use Bootstrap. Replace your body.html code with this:
  • 5. <body>  <div class="container">    <div class="row">      <h3 class="text-center" >SIMPLE METEOR CHAT</h3> <!-- text holder -->      <div class="col-md-12"> <!-- login button -->        <div class="panel panel-info">          <div class="panel-heading">            GROUP CHAT          </div>          <div class="panel-body">            <ul class="media-list">              <!-- message template -->              {{#each messages}}                {{> message}}              {{/each}}            </ul>          </div>          <!-- message textbox -->          <form class="new-message">            <div class="panel-footer">              <div class="input-group">                <input type="text" name="text" class="form-control" placeholder="Enter Message" />                <span class="input-group-btn">                  <button class="btn btn-info send" type="submit">SEND</button>                </span>              </div>            </div>          </form>        </div>      </div>    </div>  </div> </body> Then we will create several les in the imports/ui/ directory to separate each template to a different html le and js le. Create new le message.html: <template name="message">  <li class="media">    <div class="media-body">      <div class="media">        <a class="pull-left" href="#">        <img class="media-object img-circle img-responsive" src="https://lorempixel.com/60/60/people/" />        </a>        <div class="media-body" >          {{text}}        </div>      </div>    </div>  </li> </template> Create new le message.js: import { Template } from 'meteor/templating'; import './message.html';
  • 6. Open body.js and add this after import './body.html' : import './message.js'; Thank to Bootstrap we have such an elegant app: N ice, b u t it does n’t work, I can’t s en d mes s age! W h y oh wh y ? Don’t be too hurry! :-p . Now we will create a database collection to store the messages. Create a new le messages.js in the imports/api/ directory like this: import { Mongo } from 'meteor/mongo'; export const Messages = new Mongo.Collection('messages'); In MongoDB, this is how we create a collection in JavaScript: MyCollection = new Mongo.Collection("my-collection") On the server, this sets up a MongoDB collection called my-collection; on the client, this creates a cache connected to the server collection. In this demo, to make it easy, assume that the entire database is present on the client. We also import the messages.js to the server. Open the server/main.js and add this to the second line: import '../imports/api/messages.js'; Now we can display message from the collection by opening body.js and replacing the Template.body.helpers with this: import { Messages } from '../api/messages.js'; Template.body.helpers({  tasks() {    return Tasks.find();  }, }); Don’t worry when your chat group is empty. Just a few steps left then you will receive your messages. As we created the message textbox in the body.html in the previous step, now we will handle the submit event to insert new message. Add this to the end of the body.js:
  • 7. Template.body.events({  'submit .new-message'(event) {    // Prevent default browser form submit    event.preventDefault();    // Get value from form element    const target = event.target;    const text = target.text.value;    // Insert a message into the collection    Messages.insert({      text,      createdAt: new Date(), // current time //user information    });    // Clear form    target.text.value = '';    // scroll to last message    $('.panel-body').scrollTop($('.media-list').height()) }, }); Now you can say Hello world! You can open another browser window and chat to yourself to see if it works real-time. Awesome, right? Th is is n ot a ch at . Ever yon e mu s t h ave t h eir own accou n t s an d log in , righ t ? It’s simple man. If you think we have a lot of things to deal with, then you will be surprised. Just run this command: meteor add accounts-ui accounts-password This will enable Meteor accounts system and a drop-in login user interface with multi-user functionality. Then open body.html and replace the <!-- text holder --> with this: <h5 class="text-center text-muted">Sign in to join!</h5> and replace the <!-- login button --> with this: {{> loginButtons}} And add this before and after the <form> tag:
  • 8. {{#if currentUser}} <form…> … </form> {{/if}} Then we will add a new le accounts-con g.js in the imports/startup/ directory to make easier to sign up: import { Accounts } from 'meteor/accounts-base'; Accounts.ui.config({  passwordSignupFields: 'USERNAME_ONLY', }); And import it by opening client/main.js and inserting this to the rst line: import '../imports/startup/accounts-config.js'; Then you will see our app now looks like this: You can simply create account, sign in… To join our chat! Let’s add some more elds to your messages collection to see who sends it. Open the body.js and replace //user information inside the function Messages.insert with this: owner: Meteor.userId(), username:Meteor.user().username, And open the message.html, replace the <!-- user information --> with this: <small class="text-muted"><strong>{{username}}</strong> | {{createdAt}}</small> Finally, add this to client/main.css: .panel-body{  overflow-y:scroll;  height:60vh; } All done! Enjoy your Meteor chat app!
  • 9. C on clu s ion Through this simple app, we’ve discovered something more about Meteor: File structure in Meteor Blaze – Meteor’s default frontend rendering system Spacebar – Meteor’s template language How to add packages to your Meteor app Hope you nd it useful. Keep practising everyday! P.s : You can get the all code here (https://github.com/31131021883/simple-chat/). (https://www.facebook.com/sharer/sharer.php? u=https%3A%2F%2Fblog.designveloper.com%2F2016%2F06%2F13%2Fcreate- a- meteor- chat- app-in- 30- minutes%2F) (http://twitter.com/intent/tweet? source=Designveloper Software agency - Meteor prime partner&text=https%3A%2F%2Fblog.designveloper.com%2F2016%2F06%2F13%2Fcreate- a- meteor- chat- app-in- 30- minutes%2F) (https://plus.google.com/share? url=https%3A%2F%2Fblog.designveloper.com%2F2016%2F06%2F13%2Fcreate- a- meteor- chat- app-in- 30- minutes%2F) (http://www.linkedin.com/shareArticle? mini=true&url=https%3A%2F%2Fblog.designveloper.com%2F2016%2F06%2F13%2Fcreate- a- meteor- chat- app-in- 30- minutes%2F&title=Create%20a%20Meteor%20chat%20app%20in%2030%20minutes&summary=In%20the%20previous%20post%2C%20we%26%23821 time%20chat%2C%20with%20many%20users.%20Follow%20these%20steps%20and%20you%26%238217%3Bll%20 nish%20it%20in%20just%2030%20m Software agency - Meteor prime partner) (http://www.tumblr.com/share/link? url=https%3A%2F%2Fblog.designveloper.com%2F2016%2F06%2F13%2Fcreate- a- meteor- chat- app-in- 30- minutes%2F&name=Create%20a%20Meteor%20chat%20app%20in%2030%20minutes&description=In%20the%20previous%20post%2C%20w time%20chat%2C%20with%20many%20users.%20Follow%20these%20steps%20and%20you%26%238217%3Bll%20 nish%20it%20in%20just% Chat app JavaScript Meteor Real-time Get started with Meteor (https://blog.designveloper.com/2016/06/11/get-started-with-meteor/)