Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Meteor Design Patterns
Meteor Design Patterns

Meteor Design Patterns: Accelerate your code writing skills with over twenty programming patterns that will make your code easier to maintain and scale

eBook
€8.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Meteor Design Patterns

Chapter 1. Getting Started with Meteor

Meteor is a framework that is essentially fast for the purpose of development even if you program at a slow pace. The aim of this book is to increase your development speed and improve quality. There are two key ingredients required to improve development: compilers and patterns. Compilers add functionality to your coding language, while patterns increase the speed at which you solve common programming issues.

This book will mostly cover patterns, but we'll use this chapter to quick start compilers and understand how they relate to Meteor—a vast but simple topic. The compilers that we will look at are as follows:

  • CoffeeScript
  • Jade
  • Stylus

We will review some basic knowledge you should have about Meteor. This will cover the following:

  • Templates, helpers, and events
  • The event loop and the merge box
  • The must-have packages
  • Folder structure

CoffeeScript for Meteor

CoffeeScript is a compiler for JavaScript that adds "syntactic sugar" inspired by Ruby, Python, and Haskell; it effectively makes the writing of JavaScript easier and more readable. CoffeeScript simplifies the syntax of functions, objects, arrays, logical statements, binding, managing scope, and much more. All CoffeeScript files are saved with a .coffee extension. We will cover functions, objects, logical statements, and bindings as these are some of the most commonly used features.

Objects and arrays

CoffeeScript gets rid of curly braces ({}), semicolons (;), and commas (,). This alone saves you from repeating unnecessary strokes on the keyboard. Instead, CoffeeScript emphasizes on the proper use of tabbing. Tabbing will not only make your code more readable, but it will be a key factor in making the code work as well. In fact, you are probably already tabbing the right way! Let's look at some examples:

#COFFEESCRIPT
toolbox =
  hammer:true
  flashlight:false

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Here, we are creating an object named toolbox that contains two keys: hammer and flashlight. The equivalent in JavaScript will be this:

//JAVASCRIPT - OUTPUT
var toolbox = {
  hammer:true,
  flashlight:false
};

Much easier! As you can see, we have to tab to indicate that both the hammer and flashlight properties are a part of toolbox. The var word is not allowed in CoffeeScript because CoffeeScript automatically applies it for you. Let's have a look at how we would make an array:

#COFFEESCRIPT
drill_bits = [
  "1/16 in"
  "5/64 in"
  "3/32 in"
  "7/64 in"
]

//JAVASCRIPT – OUTPUT
var drill_bits;
drill_bits = ["1/16 in","5/64 in","3/32 in","7/64 in"];

Here, we can see that we don't need to have any commas, but we do need to have brackets to determine that this is an array.

Logical statements and operators

CoffeeScript removes a lot of parenthesis (()) in logical statements and functions as well. This makes the logic of the code much easier to understand at first glance. Let's look at an example:

#COFFEESCRIPT
rating = "excellent" if five_star_rating

//JAVASCRIPT – OUTPUT
var rating;

if(five_star_rating){
  rating = "excellent";
}

In this example, we can clearly see that CoffeeScript is easier to read and write. CoffeeScript effectively replaces the entire implied parenthesis in any logical statement.

Operators such as &&, ||, and !== are replaced by words to make the code more readable. Here is a list of the operators that you will be using the most:

CoffeeScript

JavaScript

is

===

isnt

!==

not

!

and

&&

or

||

true, yes, on

true

false, no, off

false

@, this

this

Let's look at a slightly more complex logical statement and see how it is compiled:

#COFFEESCRIPT
# Suppose that "this" is an object that represents a person and their physical properties

if @eye_color is "green"
  retina_scan = "passed"
else
  retina_scan = "failed"

//JAVASCRIPT - OUTPUT
if(this.eye_color === "green"){
  retina_scan = "passed";
} else {
  retina_scan = "failed";
}

Notice how the context of this is passed to the @ symbol without the need for a period, making @eye_color equal to this.eye_color.

Functions

A JavaScript function is a block of code designed to perform a particular task. JavaScript has a couple of ways of creating functions that are simplified in CoffeeScript. They look like this:

//JAVASCRIPT
//Save an anonymous function onto a variable
var hello_world = function(){
  console.log("Hello World!");
}

//Declare a function
function hello_world(){
  console.log("Hello World!");
}

CoffeeScript uses -> instead of the function() keyword. The following example outputs a hello_world function:

#COFFEESCRIPT
#Create a function
hello_world = ->
  console.log "Hello World!"

//JAVASCRIPT - OUTPUT
var hello_world;
hello_world = function(){
  return console.log("Hello World!");
}

Once again, we will use a tab to specify the contents of the function so that there is no need for curly braces ({}). This means that you have to make sure that you have the entire logic of the function tabbed under its namespace.

What about our parameters? We can use (p1,p2) -> where p1 and p2 are parameters. Let's make our hello_world function output our name:

#COFFEESCRIPT
hello_world = (name) ->
  console.log "Hello #{name}"

//JAVSCRIPT – OUTPUT
var hello_world;
hello_world = function(name) {
  return console.log("Hello " + name);
}

In this example, we can see how parameters are placed inside parentheses. We are also doing string interpolation. CoffeeScript allows the programmer to easily add logic to a string by escaping the string with #{}. Also notice that, unlike JavaScript, you do not have to return anything at the end of the function, CoffeeScript automatically returns the output of the last command.

Binding

In Meteor, we will often find ourselves using the properties of this within nested functions and callbacks. Function binding is very useful for these types of cases and helps to avoid saving data in additional variables. Function binding sets the value of the this object inside the function to the value of this outside the function. Let's look at an example:

#COFFEESCRIPT
# Let's make the context of this equal to our toolbox object
# this =
#   hammer:true
#   flashlight:false

# Run a method with a callback
Meteor.call "use_hammer", ->
  console.log this

In this case, the this object will return a top-level object such as the browser window. This is not useful at all. Let's bind this now:

#COFFEESCRIPT
# Let's make the context of this equal to our toolbox object
# this =
#   hammer:true
#   flashlight:false

# Run a method with a callback
Meteor.call "use_hammer", =>
  console.log this

The key difference is the use of => instead of the expected -> to define the function. Using => will make the callback's this object equal to the context of the executing function. The resulting compiled script is as follows:

//JAVASCRIPT
Meteor.call("use_hammer", (function(_this) {
  return function() {
    return Console.log(_this);
  };
})(this));

CoffeeScript will improve your coding quality and speed. Still, CoffeeScript is not flawless. When you start combining functions with nested arrays, things can get complex and difficult to read, especially when the functions are constructed with multiple parameters. Let's look at a common query that does not look as readable as you would expect it to be:

#COFFEESCRIPT
People.update
  sibling:
    $in:["bob","bill"]
,
  limit:1
  ->
    console.log "success!"

This collection query is passing three parameters: the filter object, the options object, and the callback function. To differentiate between the first two objects, we had to place a comma at the same level as the function and then, indent the second parameter. This is unwieldy, but we can use variables in order to make the query more readable:

#COFFEESCRIPT
filter =
  sibling:
    $in:["bob","bill"]
options =
  limit:1
People.update filter, options, ->
  console.log "success!"

Go to coffeescript.org and play around with the language by clicking on the "try coffeescript" link.

Jade for Meteor

Jade works much like CoffeeScript but it is used for HTML instead. I recommend that you install the mquandalle:jade package. All the Jade files are saved with a .jade extension. This section will cover the most used aspects of Jade in Meteor such as HTML tags, components, and helpers.

HTML tags

Much like CoffeeScript, Jade is a language that depends heavily on tabbing. When you want to add children to an HTML tag, you simply use tab. Tag IDs and classes can be added using the CSS selector notation ('input#name.first'). This means classes are expressed with a dot (.) and IDs are expressed with a pound (#). Let's look at an example:

//- JADE
div#container
  ul.list
    li(data-bind="clickable") Click me!

<!-- HTML – OUTPUT -->
<div id="container">
  <ul class="list">
    <li data-bind="clickable">Click me!</li>
  </ul>
</div>

As you can see, special attributes such as data-bind are added with parenthesis. Symbols such as <, >, and closures are not required anymore. In this example, we have a div tag with an id attribute of "container", a ul tag with a class attribute of list, and a li tag with a special attribute of data-bind.

You will find yourself using special attributes often for the input tags to add value, placeholder, and other attributes.

Templates and components

Meteor templates are Jade components. In Meteor, we define a template with the template tag and apply the special name attribute to create a reusable HTML block. In Jade, when we create a template, we create a component as well. This looks as follows:

//- JADE
template(name="landing")
  h3 Hello World!

<!-- HTML – OUTPUT -->
<template name="landing">
  <h3>Hello World!</h3>
</template>

Now we can use this template as a Jade component anywhere in our views. To call a Jade component, you simply prepend a plus sign to the name of the template. Let's look at an example where we want to place a landing page inside a main_layout page:

//- JADE
template(name="landing")
  h3 Hello World!

template(name="main_layout")
  +landing

<!-- HTML – OUTPUT -->
<template name="landing">
  <h3>Hello World!</h3>
</template>

<template name="main_layout">
  {{> landing}}
</template>

That's it! Notice that we have prepended the plus (+) sign to the name of the template to call it. This is equivalent to using {{> landing}} in SpaceBars (Meteor's version of Handlebars). Components can have parameters as well, which can be later used in the templates' instance. Let's make our example output someone's name:

//- JADE
template(name="landing")
  h3 Hello {{name}}

template(name="main_layout")
  +landing(name="Mr Someone")

# COFFEESCRIPT
Template.landing.helpers
  "name": ->
    Template.instance().data.name

<!-- HTML – OUTPUT -->
<template name="landing">
  <h3>Hello {{name}}</h3>
</template>

<template name="main_layout">
  {{> landing name="Mr Someone"}}
</template>

Adding attributes to your templates can make your templates flexible as shown in the preceding example. Still, it is unlikely that you will have to use this as templates "soak up" data from their parent context.

Helpers

Helpers in Meteor are functions that return data before rendering to the view. We use helpers for iteration, logical statements, and variables. The two basic helpers are each and if, but adding the raix:handlebar-helpers package will add a dictionary of other useful helpers to keep your code from repeating. Let's have a look at how we can use our helpers:

//- JADE
template(name="list_of_things")
  each things
    if selected
      p.selected {{name}}
    else
      p {{name}}

<!-- HTML – OUTPUT -->
<template name="list_of_things">
  {{#each things}}
    {{#if selected}}
      <p class="selected">{{name}}</p>
    {{else}}
      <p>{{name}}</p>
    {{/if}}
  {{/each}}
</template>

In this example, the each helper is iterating through the return value of another helper named things and if the selected helper resolves to true, then we will render p.selected with the name variable.

It's important to understand that everything that is not an HTML tag is a helper, and that if you want to use a helper within a tag, you need to use {{}} or #{} to express this.

Go to jade-lang.com and handlebars.js to know more specific information. With this information, you should be able to do just about anything.

Stylus for Meteor

Stylus works much like CoffeeScript and Jade but it is for CSS. I recommend that you install mquandalle:stylus. This package is preinstalled with useful tools such as Jeet and Rupture. All Stylus files are saved with a .styl extension. There are only three things that we need to learn about Stylus: CSS tags, variables, and functions.

CSS tags

Stylus is a language that does away with the need for semicolons (;) and curly braces ({}) in exchange for making good use of tabbing. Let's look at an example:

// STYLUS
// Let's make a vertical positioning class
.vertical-align-middle
  //PART 1
  position:absolute
  width:100%
  height:100%
  display:table
  overflow-x:hidden

  .special
    background:black

We can see in PART 1 how properties are defined for a class by tabbing those properties in .special is used to select an HTML tag with the special class that is a child of the vertical-align-middle class. Let's look at how PART 1 compiles:

/* CSS – OUTPUT PART 1 */
.vertical-align-middle {
  position:absolute;
  width:100%;
  height:100%;
  display:table;
  overflow-x:hidden;
}
.vertical-align-middle .special {
  background:black;
}

Now let's add a more complex selector:

// STYLUS
// Let's make a vertical positioning class
.vertical-align-middle
  //PART 1
  ...

  //PART 2
  > *
    display:table-cell
    vertical-align:middle

PART 2 has a combination of special CSS2 selectors: specific parent (>) and all elements (*). In this particular order, the CSS2 selectors are picking the "any first sibling" element only and applying the rules. Let's look at how PART 2 compiles:

/* CSS – OUTPUT PART 2 */
.vertical-align-middle > * {
  display:table-cell;
  vertical-align:middle;
}

Let's add a new class to the current class that aligns the object to the top:

// STYLUS
// Let's make a vertical positioning class
.vertical-align-middle
  //PART 1
  ...
  //PART 2
  ...
  //PART 3
  &.whole-page
    top:0

PART 3 uses an ampersand (&) to describe an element that is not a child but instead is concatenated with the extra class. Let's look at how PART 3 compiles:

/* CSS – OUTPUT PART 3 */
.vertical-align-middle.whole-page {
  top:0;
}

Variables

Unlike CSS, Stylus supports variables. This keeps a lot of things manageable when we want to make major changes to the look of our site. Suppose we have two colors that we want to use throughout our site, but we know that these colors are going to change. Let's define them as variables so that we can easily modify them later:

// STYLUS
primary-color = #ffffff
$secondary-color = #333333

.text-default
  color:primary-color
  background:$secondary-color

.text-inverted
  color:$secondary-color
  background:primary-color

Easy right? In this example, both primary-color and $secondary-color are variables. Stylus optionally supports the use of the money sign ($) to indicate a variable. This can make it easier to spot variables.

Functions/mixins

Unlike CSS, Stylus supports functions too. LESS, Stylus, and Sassy CSS (SCSS) refer to functions as mixins. Functions will make your CSS concoctions much easier to share across a project. We will cover the two types of mixins in Stylus: mixins and transparent mixins.

Mixins are functions that take a defined set of parameters. Let's take a look at how we can write a mixin:

// STYLUS
animation(duration,delay,timing)
  -webkit-animation-duration:duration
  animation-duration:duration
  -webkit-animation-delay:delay
  animation-delay:delay
  -webkit-animation-timing-function:timing
  animation-timing-function:timing

button
  animation(500ms,0,ease-out)

/* CSS – OUTPUT */
button {
  -webkit-animation-duration:500ms;
  animation-duration:500ms;
  -webkit-animation-delay:0;
  animation-delay:0;
  -webkit-animation-timing-function:ease-out;
  animation-timing-function:ease-out;
}

In this example, we first define the animation mixin, and then we apply the mixin to the button HTML tag. However, there is a much easier and effective way of doing this via a transparent mixin.

A transparent mixin, basically, takes all the parameters and saves them in an arguments variable without you having to define anything. Let's have a look:

// STYLUS
animation()
  -webkit-animation:arguments
  animation:arguments

button
  animation(pulse 3s ease infinite)

/* CSS – OUTPUT */
button {
  -webkit-animation:pulse 3s ease infinite;
  animation:pulse 3s ease infinite;
}

Notice how we did not have to define every single parameter in the mixin, and the arguments variable simply passed all the arguments that it could find. This is especially useful for keeping the code flexible.

Stylus essentially upgrades CSS in such a way that it makes the code much easier to manage and therefore, ends up saving us a lot of development time.

Go to stylus-lang.com and learnboost.github.io/stylus to learn more about Stylus.

Templates, helpers, and events

Now that we are on the same page for the languages that we are going to use throughout the book, let's do a quick review of some of the elements that we will use during our development process.

Templates, helpers, and events are used to build the frontend of your application. Using them effectively is the key to how we design our backend as well (which we will address in Chapter 2, Publish and Subscribe Patterns).

Templates

Meteor templates are the special blocks of HTML code that generate Meteor template objects (Template.<yourtemplate>). It is through Meteor template objects that we wire the HTML code to logic. People who have worked with an MVC framework will refer to these templates as views. This is a key concept to understand.

Open up your terminal and create a new project:

meteor create basic_meteor

Now let's add our languages:

meteor add coffeescript
meteor add mquandalle:jade
meteor add mquandalle:stylus

Remove the three visible files from /basic_meteor (do not remove any of the files starting with a dot), and create /client/layout.jade. This is something that exists in one way or another in every Meteor project. Let's program:

//- layout.jade
head
  title Meteor Basics
  meta(name="viewport" content="user-scalable=no, initial- scale=1.0, maximum-scale=1.0")
  meta(name="apple-mobile-web-app-capable" content="yes")
body
  +basic_template

I highly recommend adding these metatags to make your site mobile-friendly right from the beginning. With this snippet of code, we are effectively starting up the very first thing that Meteor is going to render before running any code. Once this is rendered, Jade takes care of rendering basic_template. Let's program this in a new file, /client/basic_template.jade:

//- basic_template.jade
template(name="basic_template")
  h1 Hello World!

Behind the scenes, Meteor is compiling our Jade templates and putting them all in one big file. You will never have to worry about loading basic_template.jade before layout.jade when it comes to templating.

Throughout the book, we will use meteorhacks:flow-router and meteorhacks:flow-layout to easily navigate to different templates.

Creating helpers

We have already discussed what helpers are in Jade, but how do we create helpers in Meteor? Let's go back to our basic_meteor project and create /client/basic_template.coffee. It is important to understand that Meteor helpers are used to control the variables in our template. People who have worked with an MVC framework can view this file as a controller. Let's write our first helper:

#basic_template.coffee
Template.basic_template.helpers
  "name": ->
    "Mr Someone"

Notice that the helper is defined within the helpers function of the Meteor template object: Template.<your_template>.helpers(<your_helpers>). Helpers are mostly functions that will return anything you want them to including Meteor collection cursors. Let's bring all this together now:

//- basic_template.jade
template(name="basic_template")
  h1 Hello {{name}}

This will output Hello Mr Someone inside the h1 HTML tag. Let's add a slightly more complex helper:

#basic_template.coffee
Template.basic_template.helpers
  "person": ->
    name:"Someone"
    prefix: "Mr"
    children: [
      {
        name:"Billy"
      }
      {
        name:"Nancy"
      }
    ]

//- basic_template.jade
template(name="basic_template")
  with person
    h1 Hello {{prefix}} {{name}}

    ul
      each children
        li {{name}}

In this example, we are using with to set up the data context of the HTML tags that belong to it; this data context is equivalent to person. Data context refers to the value of this inside a helper. So if you set up an object as the data context, this will be equivalent to that object. Also, we iterate through children with an each statement so that we can list out their names.

Events

Meteor taps into common JavaScript HTML events such as click, change, and focus. An event is anything that happens to an HTML element that you are listening to. Suppose we want to be able to change the name of a person to one of the children by clicking on them. We do this through the templates' event map. Let's take a look at an example of how we can do this without using reactivity or collections:

#basic_template.coffee
Template.basic_template.events
  "click li": ->
    $("h1").text "Hello #{@name}"

Easy! So to catch template events, we need to use the Template.<your_template>.events(<your_event_map>) function. In this particular example, we are using jQuery to replace text.

The event map is an object where the properties specify a set of events to be handled. These events may be specified in any of the following ways:

# Runs any time you click anywhere
"click": ->

# Runs any time you click a li element
"click li": ->

#Runs any time you click a li element OR mouseover a li element
"click li, mouseover li": ->

The key string of the event is composed of two parts: the first is always a type of event (click, hover, change, and so on) while the second is always a CSS selector.

The event loop and the merge box

Before diving into Meteor, it is critical to understand what the event loop and the merge box are and how they can adversely affect your code. Both are relatively complex in the way that they were programmed, so we will focus on understanding the general concept.

The event loop

The event loop is like a queue; it runs a series of functions one by one. Because functions are processed sequentially, each function effectively blocks others from being processed until the function is done.

In other words, the event loop functions much like a single-line conveyor belt where things are being inspected. For every inspection made, the line is stopped and nothing moves.

Meteor uses Fibers – a NodeJS library – to get around this issue. Many of the functions that you will run will be on a separate fiber. What does this mean? This means that the functions will run on a separate conveyor belt for processing. Still, not all functions are built this way, you need to make sure your server-side functions do not block the server.

So which functions could potentially cause the server to get blocked? Meteor.methods(), Meteor.publish(), and any function that does not run inside a fiber on the server. Let's see how we can unblock each one and when we should do this.

Functions defined under the Meteor.methods() that you know are going to take a long time to process, should always run on a Fiber or defer time consuming code to a Fiber. We can quickly solve this by calling the @unblock() function from within the method. Let's look at an example:

# METEOR METHODS
Meteor.methods
  #BLOCKING
  time_consuming: ->
    Meteor.setTimeout ->
        console.log "done"
      ,60000

  #NON-BLOCKING
  time_consuming_unblock: ->
    @unblock()
    Meteor.setTimeout ->
        console.log "done"
      ,60000

In this example, when you run Meteor.call("time_consuming"), the server will be blocked. When the server is blocked, other visitors won't be able to reach your site! Instead if you run Meteor.call("time_consuming_unblock"), the server will continue to function properly but consume more resources to do so.

Meteor.publish() can be easily unblocked after installing the meteorhacks:unblock package as well. This one will be particularly useful when we start to make very complex publishers that might consume a lot of resources. Let's look at an example:

# METEOR PUBLISH
#BLOCKING
Meteor.publish "external_API_query", ->
  HTTP.get "http://connect.square.com/payments"

#NON-BLOCKING
Meteor.publish "external_API_query_unblocked", ->
  @unblock()
  HTTP.get "http://connect.square.com/payments"

In this example, we are waiting for an HTTP call to respond. This will certainly block the server if we subscribe to external_API_query, so we use external_API_query_unblocked instead.

All other functions that run on the server and you know are going to block the server, should run on a fiber. Meteor has a special function to help us make this easy. It is called Meteor.wrapAsync(). Let's see how this works:

# METEOR UNBLOCKED FUNCTION
unblock_me = Meteor.wrapAsync ->
  Meteor.setTimeout ->
      console.log "done"
    ,60000

Tip

It is very important to keep the event loop in mind, especially when we're connecting our web application to external services that are going to cause massive delays to our server.

The merge box

The merge box is the algorithm that identifies all the changes that are happening to the database. It basically handles publishers, subscribers, and reactivity. The merge box also handles the initial load of data using DDP messages.

It is important to understand that we can communicate directly with the merge box via all the commands that are available to us under the Meteor.publish() function. The more optimal we can make our Meteor.publish functions, the faster the site will load.

The beginning of our online shop

Throughout the book we will be developing an e-commerce website to help us understand the core concepts of advanced Meteor web development. Let's begin by creating a new project:

meteor create online_shop

The must-have packages

Atmospherejs.com has always been the "go to" website to find packages. Here you will find thousands of packages produced by the community for free. There are a handful of packages that we absolutely need to install to make our website function properly.

First, we install the languages:

meteor add coffeescript
meteor add mquandalle:jade
meteor add mquandalle:stylus
meteor add less

Next, the router and functions that will help us with SEO and routing:

meteor add kadira:flow-router
meteor add kadira:blaze-layout
meteor add meteorhacks:fast-render
meteor add nimble:restivus
meteor add yasinuslu:blaze-meta
meteor add dfischer:prerenderio
meteor add wizonesolutions:canonical

Note

WARNING: Do not run Meteor yet! Canonical could mess up your project unless you have it set up correctly.

We will need a couple of packages as well to help us manage publishers:

meteor add lepozepo:publish-with-relations
meteor add tmeasday:publish-counts
meteor add meteorhacks:aggregate
meteor add http
meteor add meteorhacks:unblock

These next packages will extend Meteor's functions:

meteor add xorax:multiple-callbacks
meteor add aldeed:collection2
meteor add aldeed:autoform
meteor add fastclick
meteor add reactive-var
meteor add alanning:roles
meteor add accounts-password
meteor add u2622:persistent-session
meteor add ongoworks:security

We will need these packages to properly manage time:

meteor add momentjs:moment
meteor add mrt:moment-timezone

For the last set, we'll be using a couple of additional packages that will make the design process much faster:

meteor add kyleking:customizable-bootstrap-stylus
meteor add raix:handlebar-helpers
meteor add fortawesome:fontawesome
meteor add percolate:momentum

We need to remove some packages for security too:

meteor remove autopublish
meteor remove insecure

All of these packages will be explained in more detail throughout the book, but all of these are must-haves. The first package that we need to explain is the wizonesolutions:canonical package. This package makes sure that all incoming traffic is routed to your ROOT_URL, so it is particularly useful when you want all the traffic to go to your SSL site. The first thing that we need to do before running Meteor is set up canonical to run only in the production environment.

Create /server/canonical.coffee, and add this code:

#/server/canonical.coffee
if process.env.NODE_ENV is "development" or process.env.ROOT_URL.indexOf("meteor.com") > -1
  Meteor.startup ->
    process.env.PACKAGE_CANONICAL_DISABLE = true

This code snippet effectively sets your PACKAGE_CANONICAL_DISABLE environment variable to make sure that canonical is inactive while you are developing.

What are environment variables? These variables are defined within the scope of the deployment, and they make sure that the project knows information before the build finishes on the server. Information such as what database to use, which domains to use, and other setup information can usually be found in these variables. We will cover this information in the final chapter.

File structure

A proper file structure is tremendously important in Meteor. We have found that the best way to work is with functional top-level modules. This means that every folder is a micro-service, and therefore can act on its own. This allows for a lot of modularity in the project, and it's very easy for others to understand what it is that you are trying to accomplish. In this section, we will cover this file structure and Meteor's special folders.

Let's look at a sample web application folder structure:

/online_shop
/online_shop/cart
/online_shop/cart/cart_route.coffee  #RUNS ON CLIENT AND SERVER
/online_shop/cart/client
/online_shop/cart/client/cart_view.jade  #RUNS ON CLIENT ONLY
/online_shop/cart/client/cart_controller.coffee
/online_shop/cart/client/cart.styl
/online_shop/cart/server
/online_shop/cart/server/cart_publisher.coffee  #RUNS ON SERVER ONLY
/online_shop/cart/server/cart_methods.coffee

In this folder structure, cart is the micro-service, and it is composed of a route, view, controller, and publisher. The files placed under a /client directory will be published to the client and will only run on the client. The files placed under a /server directory will only run and be accessible on the server. If a file is placed in none of these directories, then the file will run on both the client and server. The expected structure goes like this:

/project_folder
/project_folder/_globals
  ./client/<global support function files>
  ./server/<global support function files>
  ./lib/collections/<collection>/<file>
  ./lib/collections/<collection>/server/<permissions file>

/project_folder/router
  ./client/layouts/<layout file>
  ./lib/<configuration file>
  ./lib/<middleware file>

/project_folder/<module>
  ./<route file>
  ./client/<template file>
  ./client/<logic file>
  ./client/<styles file>
  ./server/<publishers file>
  ./server/<methods file>

It's important to note that the /lib directory will always run before any other code does. Let's place our canonical file under the /_globals/canonical/server directory.

Let's create our first module: the router. Create the /router/client/layout.jade directory, and we will only have one layout throughout the project. Now let's code our layout:

//- LAYOUT.JADE
head
  title Online Shop
  meta(charset="utf-8")

  //- Allow saving to homescreen
  meta(name="apple-mobile-web-app-capable" content="yes")

  //- Do not try to detect phone numbers
  meta(name="format-detection" content="telephone=no")

  //- Make it mobile friendly
  meta(name="viewport" content="user-scalable=no, initial- scale=1.0, maximum-scale=1.0")

body

template(name="layout")
  +Template.dynamic(template=nav)
  +Template.dynamic(template=content)

Here, we have introduced the Template.dynamic component. This component may be used to render other templates dynamically by changing the value of a variable to the name of the template we want to render. We decided to use two variables—nav and content— that are controlled by the router. So, basically, the content variable will be changing to different strings that are equal to the names of our templates.

We will create our landing module in the next chapter to learn not only how to use the router but also how to properly subscribe to data.

Summary

We have addressed a lot of things in this chapter. We can now program faster because we have tools such as CoffeeScript, Jade, and Stylus to help us. Also, we have learned how to use templates, helpers, and events to work with our Meteor frontend. Understanding the event loop and the merge box has made us a bit more precautious when it comes to running complex, time-consuming operations. Finally, we began to build a project, and we adopted a folder structure that is going to make development quicker.

In the next chapter, we will cover two of the most important parts that make a Meteor application viable: Meteor publishers and Meteor subscribers. With these patterns, you will be able to produce sites that load quickly and that do not put too much strain on the server.

Left arrow icon Right arrow icon
Download code icon Download Code

Description

With the increasing interest in NodeJS web applications, a new framework, Meteor, has joined the ranks to simplify developer workflows. Meteor is one of the few open source frameworks that has received funding since its early development stages. It builds on ideas from existing frameworks and libraries, offering developers an easy way to develop a prototype app. At the same time, it gives them the tools and flexibility to build a fully fledged production app. Meteor is the weapon of choice for start-ups in today’s world. Meteor Design Patterns cuts through the jargon that most websites play with and gets to the point with simple solutions that will boost your development skills. We start off with a refresher on the basics of JavaScript programming such as templates, CoffeeScript, the Event Loop, and the Merge Box, amongst others. You then learn how to map real-world data and optimize the data’s publishers to output data with the least amount of work done by the server with some subscribe and publish patterns. Next, using front-end patterns, you will learn how to create maintainable and trackable forms, and make our site crawlable by any search engine. Following this, you will see how to optimize and secure the web application and maintain applications without breaking other features. Finally, you will learn how to deploy a secure production-ready application while learning to set up modulus, compose with Oplog tracking and SSL certificates, as well as error tracking with Kadira. Throughout the book, you will put your skills to practice and build an online shop from scratch. By the end of the book, you will have built a feature-rich online shop.

Who is this book for?

This book is for developers who have already had an introductory course with Meteor. Basic knowledge of web development is recommended.
Estimated delivery fee Deliver to Denmark

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 21, 2015
Length: 184 pages
Edition : 1st
Language : English
ISBN-13 : 9781783987627
Vendor :
Meteor Development Group
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Denmark

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Oct 21, 2015
Length: 184 pages
Edition : 1st
Language : English
ISBN-13 : 9781783987627
Vendor :
Meteor Development Group
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 83.97
Meteor Design Patterns
€29.99
Meteor Cookbook
€32.99
Building Single-page Web Apps with Meteor
€20.99
Total 83.97 Stars icon
Banner background image

Table of Contents

7 Chapters
1. Getting Started with Meteor Chevron down icon Chevron up icon
2. Publish and Subscribe Patterns Chevron down icon Chevron up icon
3. Front-end Patterns Chevron down icon Chevron up icon
4. Application Patterns Chevron down icon Chevron up icon
5. Testing Patterns Chevron down icon Chevron up icon
6. Deployment Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(6 Ratings)
5 star 50%
4 star 33.3%
3 star 0%
2 star 16.7%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




rsundar Nov 19, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A very useful resource to take your meteor skills to the next level. Shows you how you can deploy your meteor applications in a production setting and use Kadira to enhance it's performance. All in all definitely recommended for someone who has a good grasp on the basics of the meteor framework.
Amazon Verified review Amazon
James Coles Oct 28, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I had this book on preorder the moment I saw it on Amazon. It arrived and I read it within the day. I've got 4 books on Meteor in total and this one is by far the best one I have read so far. It's the story told from start to end. It's not a lose collection of recipes it as the cookbooks and it's not a half hearted approach to explain a few features or modules as other books on the market. This is a reference and a milestone book for meteor. If you want to get serious about this framework. Get this book.If I have one concern it is that the book is using coffeescript, stylus and jade, but it's simple enough to translate this to javascript, scss and html templates when needed.
Amazon Verified review Amazon
Lars Lemos Dec 04, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I come from a Java EE background so was looking for a fast paced recipes book.Found exactly what I needed.This book contains this most fundamentals instructions from how to set up your development environment from scratch to the introduction to the Front-end patterns and Application patterns, it also include testing Patterns and the most important how to deploy our app to the cloud services.Although being a small book, the author was able to compact all the necessary information for the best understanding of the reader.I advice to read this book along with some other reference book or documentation to make the most out of the content that the patterns describe.What fascinated me more in this book was the fact that I was not expecting to find instruction on how to put my app in production since by the name "Meteor Design Patterns", so you get more than you expected.The book is worth reading and future reference.
Amazon Verified review Amazon
Kevin Nicholas Casault Nov 24, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Let me start by saying I am not a Meteor expert just someone in the process of learning Meteor. Also just to be clear when you read design patterns in the title think reusable solutions or good practices not along the concept of the Gang of 4 design patterns. I feel like the advice in the beginning of the book about using JavaScript (Coffee) and CSS (Stylus) preprocessors and HTML (Jade) template engines could probably be used with any modern JavaScript framework. Probably good advice in general. From Chapter 2 on the book is much more Meteor specific in the solutions it presents. The different types of variables available to Meteor applications was a good discussion for example. As someone learning Meteor, many of the patterns were very helpful as I think about building Meteor applications and what needs to be done to make a Meteor application search engine friendly.The product order/shopping cart example used through out the book is helpful and easy to understand as the features are added to it through out the book.The book has been a good learning tool and I can see it being a good tool to refer to in the future as well. The design patterns presented should be helpful even as Meteor matures and changes of time.There are also many atmosphere packages discussed and recommended in the book to help solve specific problem this is a nice add because searching through packages can be a time consuming.
Amazon Verified review Amazon
eskadah Nov 20, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
At the time of writing, this book is one of the few advanced level books on Meteor that are available on the market. This book guides the reader on a number of best practices for real world meteor development.Furthermore, the author of the book has a number of open source meteor packages that I have found very useful in my own work. So he definitely knows what he is talking about. For instance, the author does a good jobexplaining the importance of reactive joins in Meteor projects, the author illustrates the problem from a UI /UX perspective but ultimately breaks down the technical DDP aspects of the problem and mostimportantly provides practical solutions to implementing reactive joins in Meteor. I am giving this book 4 stars for a number of reasons. Given the fact that the code samples are in CoffeeScript,the editing could be better. Its a bit of a chore to read and understand a code sample given the liberal use of tabs, lack of commas and absent parentheses. This point brings me to my second gripe with the book.The book is very opinionated. The author tries to mitigate this in the first chapter but one chapter to introduce Coffeescript, Jade and Stylus is not enough. Readers that are not already versed in these technologies will not be able to gain much from this book.All in all, its a very good intermediate/advanced level book on Meteor. Beginners to the Meteor framework should probably look elsewhere for an introduction but they should definitely come back once they are looking for more advanced knowledge
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela