Meteor - Basic

meteor

What is a Meteor developer account?

Your account is one username that identifies you across the Meteor community. You can use it to deploy apps, publish packages, and log into developer tools and services. https://www.meteor.com/auth/dialog

How can we install Meteor?

Meteor supports OS X, Windows, and Linux, and is simple to install. The command line installer supports Mac OS X 10.7 (Lion) and above, and Linux on x86 and x86_64 architectures. The Windows installer supports Windows 7, Windows 8.1, Windows 10, Windows Server 2008, and Windows Server 2012.

On OS X or Linux, install the latest official Meteor release from your terminal:

curl https://install.meteor.com/ | sh

On Windows, download the official Meteor installer.

Meteor is by far the easiest development environment to install, with just a one line command that installs a database, development server, and a command line program, which takes care of creating and deploying your applications. http://code.tutsplus.com/tutorials/whats-this-meteor-thing--net-25426

How can we create those demo apps?

meteor create --example leaderboard
meteor create --example todos
meteor create --example localmarket

We can then navigate to one of the project’s folder and use the meteor run command to start the local server:

cd todos
meteor run

We can now play around with the code within the project folder while seeing the changes automatically reflected from within a web browser.

How can we create our own meteor web app?

meteor create webAppName
cd webAppName

Take a look inside your application directory:

client/main.js        # a JavaScript entry point loaded on the client
client/main.html      # an HTML file that defines view templates
client/main.css       # a CSS file to define your app's styles
server/main.js        # a JavaScript entry point loaded on the server
package.json          # a control file for installing NPM packages
.meteor               # internal Meteor files
.gitignore            # a control file for git
meteor npm install
meteor

Open your web browser and go to http://localhost:3000 to see the app running. Try editing the text in <h1> inside client/main.html using your favorite text editor. When you save the file, the page in your browser will automatically update with the new content. We call this "hot code push".

Here is the structure of the todos app:

imports/
  startup/
    client/
      index.js                 # import client startup through a single index entry point
      routes.js                # set up all routes in the app
      useraccounts-configuration.js # configure login templates
    server/
      fixtures.js              # fill the DB with example data on startup
      index.js                 # import server startup through a single index entry point

  api/
    lists/                     # a unit of domain logic
      server/
        publications.js        # all list-related publications
        publications.tests.js  # tests for the list publications
      lists.js                 # definition of the Lists collection
      lists.tests.js           # tests for the behavior of that collection
      methods.js               # methods related to lists
      methods.tests.js         # tests for those methods

  ui/
    components/                # all reusable components in the application
                               # can be split by domain if there are many
    layouts/                   # wrapper components for behaviour and visuals
    pages/                     # entry points for rendering used by the router

client/
  main.js                      # client entry point, imports all client code

server/
  main.js                      # server entry point, imports all server code

Inside the project directory, you will find three files: a JavaScript, HTML, and CSS file. Open the HTML file, and replace its contents with the following:

<head>
  <title>Products</title>
</head>

<body>
  {{> Products}}
</body>

<template name="Products">
    {{#each ProductArr}}
        <div class="Product">
            <h2>{{Name}}</h2>
            <p>Price: ${{Price}}</p>
            {{#if this.InStock}}
                <p>This Item is in stock</p>
            {{else}}
                <p>This Item is currently sold out</p>
            {{/if}}
        </div>
    {{/each}}
</template>

For this example, we are building a Meteor application that takes an array of JSON objects, one for each product, and displays the name, price, and availability.

We've created a template for our products, which basically just cycles through each one and displays the name, price, and availability. Now, let's open up the JavaScript file and replace everything within the Meteor.is_client if statement:

var Products = new Array(
        { Name    :  "Screw Driver",
          Price   :  "1.50",
          InStock :  true },

        { Name    :  "Hammer",
          Price   :  "3.00",
          InStock :  false }
);

Template.Products.ProductArr = function(){
    return Products;
};

Whatever is inside the Meteor.is_client section is run only on the client. Most of our code will be placed within here. The JavaScript is what you might expect: an array to hold the products, and the ProductsArr variable that we defined in the template. To test your application, simply type "meteor" in the Terminal, and Meteor will launch the development server for you to test your application.

Look at the content of the HTML file and the content of the JavaScript file above. There are some strings such as "Products" and "ProductArr" that are common. I think Meteor somehow use this to recognizes that this section of the page relies on the Products array, so it will monitor that variable and, anytime it changes, (i.e you add an item) Meteor will automatically update the page with your new changes.

What is Optimistic UI?

So why do we want to define our methods on the client and on the server? We do this to enable a feature we call optimistic UI. When you call a method on the client using Meteor.call, two things happen in parallel:

  1. The client sends a request to the server to run the method in a secure environment, just like an AJAX request would work
  2. A simulation of the method runs directly on the client to attempt to predict the outcome of the server call using the available information

What this means is that a newly created task actually appears on the screen before the result comes back from the server. If the result from the server comes back and is consistent with the simulation on the client, everything remains as is. If the result on the server is different from the result of the simulation on the client, the UI is patched to reflect the actual state of the server.

Where can we find and install packages?

Packages are basically plugins for your Meteor projects. They make it easy to quickly add features to your applications using the command line. There’s a number of official packages included with every installation of Meteor, but there’s also thousands of third-party packages available online. Originally, these packages were only available through http://atmospherejs.com — a community-run site. But while that site remains a great resource for browsing packages, there’s now an official package server. Because of this change:

  1. You don’t need to install anything extra to add packages to a project. You just use the meteor add command, followed by the name of a package.
  2. You can search for packages from the command line with the meteor search command (and use the meteor show command to see the details of a package).

How can we run one line of code on both the client and the sever and have it do different things in either environment?

When the statement to create a collection runs on the server it creates a collection. But when that same statement runs on the client, it creates a purely local collection within the user’s browser. The user then interacts with the local collection directly, which is why the data on their screen can change instantaneously, while the local and server-side collections are seamlessly synced in the background.

This doesn’t require any special treatment. You write one line of code and are provided with a boat-load of functionality in addition to being able to use a familiar syntax throughout the development cycle.

A Meteor application is seen by browsers, proxy servers, routers and other network components as a typical web application. Yet Meteor is comprised of two main components: a part that runs inside the browser and another part that runs inside the server. These two parts are configured to communicate with each other in a way that’s similar to modern web applications. Meteor allows developers to build applications without worrying about the complexities of client-server connectivity.

Folder names matter to Meteor. Anything you put in a folder called ‘server’ will only be run on the server. And anything in a ‘client’ folder will be run on the client. Code in other folders, such as ‘lib’, are run on both (yes you will be writing code that is run on both - defining your data collections, for example). You are not limited to folder naming; even in files outside of these ‘server’ and ‘client’ folders, you can simply write:

if(Meteor.isClient){
  // do client stuff
}

// OR

if(Meteor.isServer){
  // do server stuff
}

Why does Meteor need sticky session?

What does Meteor do with HTML files?

Meteor parses HTML files and identifies three top-level tags: <head>, <body>, and <template>. Everything inside any <head> tags is added to the head section of the HTML sent to the client, and everything inside <body> tags is added to the body section, just like in a regular HTML file.

Everything inside <template> tags is compiled into Meteor templates, which can be included inside HTML with > templateName or referenced in your JavaScript with Template.templateName.

Also, the body section can be referenced in your JavaScript with Template.body. Think of it as a special "parent" template, that can include the other child templates.

When we create an application, what are the default files?

The default client/main.html file:

<head>
  <title>grill</title>
</head>

<body>
  <h1>Welcome to Meteor!</h1>

  {{> hello}}
  {{> info}}
</body>

<template name="hello">
  <button>Click Me</button>
  <p>You've pressed the button {{counter}} times.</p>
</template>

<template name="info">
  <h2>Learn Meteor!</h2>
  <ul>
    <li><a href="https://www.meteor.com/try" target="_blank">Do the Tutorial</a></li>
    <li><a href="http://guide.meteor.com" target="_blank">Follow the Guide</a></li>
    <li><a href="https://docs.meteor.com" target="_blank">Read the Docs</a></li>
    <li><a href="https://forums.meteor.com" target="_blank">Discussions</a></li>
  </ul>
</template>

client/main.css:

This file is just an empty file.

The default client/main.js file:

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';

Template.hello.onCreated(function helloOnCreated() {
  // counter starts at 0
  this.counter = new ReactiveVar(0);
});

Template.hello.helpers({
  counter() {
    return Template.instance().counter.get();
  },
});

Template.hello.events({
  'click button'(event, instance) {
    // increment the counter when button is clicked
    instance.counter.set(instance.counter.get() + 1);
  },
});

The default server/main.js file:

import { Meteor } from 'meteor/meteor';

Meteor.startup(() => {
  // code to run on server at startup
});

How can we do minification?

We do not have to do minification. We can just write Javascript/CSS files and don’t even have to include them in the head of your page - Meteor rounds them all up, minifies them and puts them in your app for you.

What is DDP?

DDP is the heart of MeteorJS and it’s the protocol Meteor uses to communicate between the client and the server. DDP is an acronym for Distributed Data Protocol. Meteor has implemented both client and server implementations for DDP. There are a few client libraries for other frameworks and languages for connecting with Meteor via DDP.

DDP is very simple and minimalistic. It is a protocol based on JSON. Technically, DDP can be implemented on top of any duplex transport. Meteor’s current implementation is based on WebSockets and SockJS. SockJS is a WebSockets emulation transport, which can be used when WebSockets is not available.

DDP mainly does two things:

  1. It handles Remote Procedure Calls (RPC).
  2. It manages data.

With RPC, you can invoke a method on the server and get something back in return. Besides that, DDP has a nice feature: it notifies the caller after all the write operations in the method have been reflected to all the other connected clients.

What are the two types of servers?

Although Meteor runs on a single port, internally it works as two separate servers:

  1. HTTP Server: is used to serve static files and HTTP requests. Meteor uses the connect Node.js module for this purpose.
  2. DDP Server: handles all publications, MongoDB operations and Meteor methods.

What is the relationship between DDP and SockJS?

Meteor uses SockJS as the transport protocol. In actuality, the DDP server is a SockJS server customized for Meteor.

Does Meteor support ES2015?

Yes. If you haven't tried next-generation JavaScript features yet, some of the syntax in the intial app code, and throughout this tutorial, might look weird. This is because Meteor ships by default with support for many features of ES2015, the next version of JavaScript. Some of these features include:

  1. Arrow functions: (arg) => {return result;}
  2. Shorthand for methods: render() { … }
  3. const and let instead of var
  1. https://docs.meteor.com/#/full/ecmascript
  2. http://git.io/es6features
  3. https://github.com/getify/You-Dont-Know-JS/tree/master/es6%20%26%20beyond
  4. https://github.com/nzakas/understandinges6
  5. https://guide.meteor.com/code-style.html#ecmascript

What is in the default client/main.html file?

<head>
  <title>grill</title>
</head>

<body>
  <h1>Welcome to Meteor!</h1>

  {{> hello}}
  {{> info}}
</body>

<template name="hello">
  <button>Click Me</button>
  <p>You've pressed the button {{counter}} times.</p>
</template>

<template name="info">
  <h2>Learn Meteor!</h2>
  <ul>
    <li><a href="https://www.meteor.com/try" target="_blank">Do the Tutorial</a></li>
    <li><a href="http://guide.meteor.com" target="_blank">Follow the Guide</a></li>
    <li><a href="https://docs.meteor.com" target="_blank">Read the Docs</a></li>
    <li><a href="https://forums.meteor.com" target="_blank">Discussions</a></li>
  </ul>
</template>

The main.html file above define and use 2 templates (hello and info)

What is in the default client/main.css file?

It is just an empty file.

What is in the default client/main.js file?

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';

Template.hello.onCreated(function helloOnCreated() {
  // counter starts at 0
  this.counter = new ReactiveVar(0);
});

Template.hello.helpers({
  counter() {
    return Template.instance().counter.get();
  },
});

Template.hello.events({
  'click button'(event, instance) {
    // increment the counter when button is clicked
    instance.counter.set(instance.counter.get() + 1);
  },
});

What is in the default server/main.js file?

import { Meteor } from 'meteor/meteor';

Meteor.startup(() => {
  // code to run on server at startup
});

What is the meteor build tool?

The Meteor build system is the actual command line tool that you get when you install Meteor. You run it by typing the meteor command in your terminal, possibly followed by a set of arguments. Read the docs about the command line tool or type meteor help in your terminal to learn about all of the commands.

The Meteor build tool is what compiles, runs, deploys, and publishes all of your Meteor apps and packages. It’s Meteor’s built-in solution to the problems also solved by tools like Grunt, Gulp, Webpack, Browserify, Nodemon, and many others, and uses many popular Node.js tools like Babel and UglifyJS internally to enable a seamless experience.

  1. Reloads app on file change: When you run meteor, the tool starts up, and you should leave it running continuously while developing your app. The tool automatically detects any relevant file changes and recompiles the necessary changes, restarting your client or server environment if needed.
  2. Compiles files with build plugins: The main function of the Meteor build tool is to run “build plugins”. These plugins define different parts of your app build process. Meteor puts heavy emphasis on reducing or removing build configuration files, so you won’t see any large build process config files like you would in Gulp or Webpack. The Meteor build process, and file load order, is configured almost entirely through adding and removing packages to your app and putting files in specially named directories. For example, to get all of the newest stable ES2015 JavaScript features in your app, you just add the ecmascript package. This package provides support for ES2015 modules, which gives you even more fine grained control over file load order using ES2015 import and export. As new Meteor releases add new features to this package you just get them for free.
  3. Combines and minifies code: Another important feature of the Meteor build tool is that it automatically concatenates and minifies all of your files in production mode. This is enabled by the standard-minifier-js and standard-minifier-css packages, which are in all Meteor apps by default. If you need different minification behavior, you can replace these packages. Below, we’ll talk about how to switch out a minifier to add PostCSS to your build process.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License