Ghost Themes
SimpleChat.Support - Open Source Live Chat App
0%
Why Front-End Developers should try to learn Meteor
words - read.

Why Front-End Developers should try to learn Meteor

There are so many great front-end developers or web designers out there which don't want to dig into backend coding lessons, and I really understand that very well. Let them do what they do best. Everyone wants to have some kind of smooth start and build their original website at some point in their careers or just for fun. Even if they are very good at HTML and CSS it could be hard for them to just start the backend part of their project. Or even if they just want a simple static website without any backend programming, they surely need to host it somewhere. They need to deploy their simple website. They need to take care of it and sometimes this could be a problem. The wrong decisions could block them in the future when they start thinking about some backend functionalities.

This is a very common situation and we have many simple solutions for it. We have cloud apps like Webflow which are excellent, in my opinion. We have also a number of static website builders and generators like Jekkyl. But sometimes you are just between 'I want it fast and I don't care how I achieve it' and 'I want it fast and I like to do it myself to gain more control and knowledge'. This article is for people from the second group.

So, not a programmer? (or not yet)? Do you have knowledge of HTML and CSS and maybe a little jQuery too? Do you want to learn something which doesn't take much time and will be very useful in your job? Then just jump in and read this!

What we'll cover here is:

  • Meteor as an 'almost-no-config' programming platform, not only a JavaScript framework
  • HTML, CSS and JavaScript is all you need – file structure and relations
  • HTML templates and CSS processing
  • JavaScript/jQuery events and life cycle callbacks
  • Working with a ready-to-use database without any configuration
  • Put your website on the server with only one command
  • Hybrid mobile apps with Meteor

Of course this is only an introduction to Meteor. I want to show how helpful it is especially for non programmers. If you want to read more on each of the topics you should probably Google it, but here we will cover the basics and some good tips to know.

What’s so special about Meteor?

Apart from the fact that it is a very good tool with full stack reactivity, live data sync, great MongoDB support, DDP protocol and Websockets, it has some cool features which could be appreciated by front-end developers.

People who are not programmers will surely agree with me that configuring your workspace for programming technologies is complicated. We need to configure local servers, databases, environmental variables and more and so on. Also we probably need some 'big' IDE to work on our project. These could be the worst parts of programming and we need to face it just in the beginning. But wait, this isn't true with the Meteor platform...

All you need to start with Meteor is your Operating System with Meteor tools installed. Yes, this is a command line work, but don't be afraid of it. This is a very simple process. If you are using Windows, there is a brand new Meteor Installer but I strongly recommend you work with Linux or OSX. Windows support is something new and sometimes it can be buggy. Of course it depends what you want to do with it but in most cases it works very well. Below you will find the official instructions about it.

Meteor Installation instructions and jump-start tutorial: https://www.meteor.com/install

You have to install Meteor tools by running one command:

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

Then you will be able to create your first app by running 'meteor create app-name'. See how it is described here: https://www.meteor.com/try

We will take another path. Meteor 'create' command will serve you only three example files. We want to talk about folder structure so we will start with Meteor boilerplate. You can read about it here: https://github.com/juliancwirko/scotty

You need git to run the example code:

$ git clone https://github.com/juliancwirko/scotty.git

or just download the .zip file...

Go to the 'scotty' folder and see what we've got there...

After that you can run the Scotty boilerplate. You have your full Meteor platform working. Just run 'meteor' in your 'scotty' folder. Meteor will run a local server on port 3000. So go to the url: http://localhost:3000.
This is really simple, isn't it? You've just installed it with a one line command and you have a full stack programming platform running.

What's more?

You’ve probably heard about Grunt, Gulp or Webpack building tools. Or maybe about Less, Sass or Stylus preprocessors? All these tools are here to help us prepare our production ready files. So they are responsible for javascript compression and css compilation. It’s really cool. You can also run your local server and watch for changes, but you have to prepare all these tools by yourself. There is always additional work to be done, but not with Meteor. Meteor provides all of it from the start. You will have your localhost server running and all changes will autoreload your page. It also provides many packages which add build plugins like Stylus or Coffeescript. For example, you can run 'meteor add juliancwirko:s-grid' and you will have the Stylus build plugin with configuration options and with s-Grid system for Meteor. More about it here: http://julian.io/s-grid-working-with-flexible-box-layouts/

Packages are another thing which makes Meteor so special. Now on Atmosphere (Official packages repository https://atmospherejs.com/), there are plenty of useful packages such as routers, UI components, UI frameworks like Bootstrap or Foundation, Accounts services etc. You want fancy alerts? Just add a package 'meteor add juliancwirko:s-alert' More here: http://s-alert.meteorapp.com

Deployment. This is also something where Meteor shines. You probably want to put your website on the server and it’s so simple with Meteor. Check out Meteor Galaxy.

File structure and relations

Meteor doesn't tell you how you should scaffold your app. You can place your files wherever you want in the project root directory. However there are some special folders and some special rules.

First of all you shouldn't touch the '.meteor' folder. This is a special Meteor folder where it keeps all its built files. See example here: https://github.com/juliancwirko/scotty/tree/master/.meteor But still, it is something that will be autogenerated after app startup so you don't have to worry about it.

Next we have special folders named 'server' and 'client'. These ones are very important because here we can decide which part of our JavaScript code will land on the server and which on the client. Meteor can use the same codebase on the server (running on the Node.js backend) and on the client (running in the browser). All other files will expose code on both sides. So here in the Scotty boilerplate we have 'server', 'client' and 'common' folder.

We will leave the server side part for now and come back to it later.

Read about file structure and relations in the Official Meteor Guide:

HTML templates, and CSS processing

In Meteor you will write only in JavaScript, HTML (actually Spacebars - Handlebars-like templating system) and CSS. This is super cool especially when you don’t have any good backend programming background.

Take a look at the 'client' folder of the https://github.com/juliancwirko/scotty/tree/master/client
Here we have some subfolders, and again Meteor isn't a particularly picky system (at least for now). You can put here all your files without dividing it into subfolders and that’s ok too.

What it's really important is that you don't have to worry about your file relations. Meteor is based on autogenerated main HTML structure and it will include all your templates the way you told it to do no matter where you put them. You can treat it like a system with many partial subtemplates. Let’s see an example. In the 'client/views/index' folder index we have two example files. One is the .html file and the second is a standard .js file. 'index-view.html' file will take its logic from 'index-view.js' file and everything will be included in the layout.html file which is the main template. In Scotty it is based on routing, but a very simple example is shown here: https://www.meteor.com/try/2 There will be also a simple example below.
Always remember that file names are totally unimportant. You can name it whatever you want, but be careful with template names.

Let’s go back to our index-view.html file. Here we have standard html between 'template' tags. All templates should have <template name=”templateName”>(...)</template> tags. It isn't important where they are placed. You can put it all in one .html file or a couple .html files. You decide. Templates use special Spacebars (like Handlebars) curly brace helpers. This is the place where your dynamic data comes in. You can prepare this data in your index-view.js file like in the example. As you can see in the index-view.js file we have a special helpers map. First of all we need to tell Meteor in which template we have helpers. So we can do it by: Template.nameOfTheTemplate.helpers({...})
In the example file we have used static data. But it could also be dynamic data from your database collection or from data sources like REST APIs.

See a very good article about Meteor Spacebars here: http://meteorcapture.com/spacebars/ , for more information about tools provided by Spacebars and how to use it.

We can sum it up with a simple example of a template and the helpers in it.

template-example.js file:

Template.templateExample.helpers({  
    testHelperData: function () {
        return {
            text1: 'This is my text one',
            text2: 'This is my text two'
        }
    }
});

template-example.html file:

<template name=”exampleTemplate”>  
    <div>
        {{#with testHelperData}}
            <div>{{text1}}</div>
            <div>{{text2}}</div>
        {{/with}} 
    <div>
</template>  

main.html file:

<body>  
    {{> templateExample}}
</body>  

As you can see this is a really simple example but still very useful. We have the main.html file which includes the templateExample template. Again, it doesn't matter how your files are named. You should only be careful with template names. In the template-example.html file you just tell Meteor which data it should use and you can print elements from that object. Here there is text1 and text2. So in the end you will have:

<div>  
    <div>This is my text one</div>
    <div>This is my text two</div>
</div>  

You’re probably wondering why the main template is not formated well. Where is the html tag etc.? This is how it goes with Meteor. You don't have to write it, but you can add, for example, a body tag or a head tag. It is also not necessary though. For example if you want to pass some special meta tags or links in the head you can do something like here. Anyway Meteor will merge all your body tags and all your head tags into one main html structure, so you don't have to worry about it. It’s normal in Meteor.

Read more about templates helpers in the official Meteor documentation:

Ok, and what about CSS?

With css it is even simpler. You can put your css files wherever you want in the client folder. Meteor will find it and merge it into one big css file with zero configuration. This is a really cool feature. Also when you use Stylus preprocessor it will work the same way. See, for example, Scotty styles folder. We have used the s-Grid system with Stylus build plugin here. You need to put your .styl files and Meteor will do all compiling for you. It will simply find those files, compile it and merge your all compiled css files. You don't need to set up your destination paths etc. Just place your .styl files.

JavaScript/jQuery events and life cycle callbacks

You’re probably thinking – this is great, but I know so many cool jQuery plugins and tools, what about that?
If you come from a jQuery background you should take some time and start thinking a little differently. Meteor has jQuery as a core dependency so you can use it. You don't have to write your code only in vanilla JavaScript, although there are some things that you should remember. All jQuery plugins are based on DOM load and ready state. Here with Meteor we should do it in a different way. So, let’s take, for example, a simple datepicker jQuery plugin. Usually you will write it like:

<html>  
    <script src="jquery.js"></script> 
    <body> 
        <p>Date: <input type="text" id="datepicker"></p> 
        <script> 
            (function () { 
                $('#datepicker').datepicker();            
            })() ;
        </script> 
    </body> 
</html>  

This is a standard and simple usage example. With Meteor all templates have their own life cycles. So you can't wait for the DOM ready. You should wait for the template onRendered event. In Meteor there are 3 life cycle events:

Template.myName.onCreated(function () {…});  
Template.myName.onRendered(function () {…});  
Template.myName.onDestroyed(function () {…});  

It is normal that you should have your datepicker input in the DOM if you want to attach the jQuery plugin to it. So how it will work in Meteor? It is important that you always try to move your jQuery DOM elements into separate templates. (This will avoid future problems with scopes and life cycle of subtemplates):

main.html file:

<body>  
    <p> Date: {{> datepickerInput}} </p>
</body>

<template name=”datepickerInput”>  
    <input type="text" id="datepicker">
</template>  

main.js file:

Template.datepickerInput.onRendered(function () {  
    this.$('#datepicker').datepicker();
});

Template.datepickerInput.onDestroyed(function () {  
    this.$('#datepicker').datepicker('destroy');
});

As you can see we attach the jQuery plugin in onRendered callback and we need to destroy it in onDestroyed callback. Why do we need to move input to another theme? Why it is better? First of all it offers more control and you can think of it like some kind of component. If you have very complex templates you could have a hard time when there’s a need to debug it.

You probably noticed that we have 'this' keyword here, before the standard jQuery dollar sign. This will narrow our element scope only to the datepickerInput template. The 'this' here is our template DOM element. So it is better to select your elements starting from the current template and not globally.

Read more about template life cycle in the official Meteor documentation:

Ok, what's about jQuery/JavaScript events?

Ok, we have some knowledge about passing data and using jQuery plugins, but how we can interact with our DOM elements?

Meteor provides events maps. This is similar to Backbone event maps.

Let’s say we have a button. We want to click on it and log some information to the console.

example.html file:

<template name=”example”>  
    <button class=”js-button-click-test”>Click me!</button>
</template>  

example.js file:

Template.example.events({  
    'click .js-button-click-test': function () {
        console.log('This is a test message!');
    }
});

This is how it is done in Meteor. Forget about jQuery here. You don't need to use $('.js-button-click-test').on('click', function () {….}); etc. Of course if you attach it to the onRendered callback it should work too, but you must remember to clean it in onDestroyed callback. But you shouldn't use jQuery events in this way.

You can use all standard events like mouseenter, blur, change etc. and you can also use your custom events here.

The first element in the string is always an event name, the second is the element selector. This is a rather clear approach.

You can read more about template events in the official Meteor documentation:
http://docs.meteor.com/#/full/eventmaps

Ok, let’s go back to our server stuff.

Working with ready to use database (...without any configuration)

What is really cool for front-end developers here is that using your backend data storage is as simple as writing your dummy jQuery plugin ;)

Meteor officially supports MongoDB, and it does it really well. In the future we should expect some more database engines. For now let’s think about MongoDB. This is NoSQL database with Javascript-like API, so this is a very good choice here.

Meteor is also special in this case, because it keeps the same database API on the server and client. So you can do the call to the database from the browser console.

You should expose to the client only that data which is safe and only when it is intended to. Then you can make some operations on it. This is good because you have latency compensation here, which means that your changes will be visible immediately and then the server will correct it if necessary.

Ok so how to set up a collection in Meteor?

You need only one line of code to do this:

MyCollection = new Mongo.Collection('myCollection');  

That's it! Now you have your collection on the server and its copy on the client.
This code should be placed on both sides (server, and client) so we could place it in, for example in the 'common' folder in your root directory.

Of course you can go and read more about MongoDB. Here we will take a look at only very basic operations.
If you want to insert something into your database you can simply call:

MyCollection.insert({someData: 'test test'});  

You can do this on the server or on the client.
Let’s see one simple example. I want to store my TODO items. Also I want to list them all on the page and have the option of adding new ones.

In the 'common' folder (visible on the server and client side of the app) you can create your file with a collection. We can call it 'collections.js' Inside we put our code:

Todo = new Mongo.Collection('todo');  

As you can see the 'Todo' variable should be a global.

Next in the 'client' we should prepare our template and our helpers with data from the Todo collection. In the client folder create todo.html and todo.js files. In todo.html we can put the code:

<template name=”todo”>  
    <ul>
        {{#each todos}}
            {{> todoItem}}
        {{/each}}
    </ul>
</template>

<template name=”todoItem”>  
    <li>{{title}} - {{description}}</li>
</template>  

In todo.js file we can place the code like below:

Template.todo.helpers({  
    todos: function () {
        return Todo.find({});
    }
});

All could be wrapped in the main.html file which could look like:

<body>  
    {{> todo}}
</body>  

Ok, let’s see what we've got here. First of all we have our main template called todo. Then we've used the todos helper to return the MongoDB cursor with all our data from the collection (it is empty for now, but the query will work just fine). Then we have used 'each' Spacebar helper to iterate through the collection and print the title and description of the todo items.

We have our listing and now we’d like to add some new todo items.

In the 'client' folder in todo.html file we need our form.

<template name=”todo”>  
    <ul>
        {{#each todos}}
            {{> todoItem}}
        {{/each}}
    </ul>
    <form id=”todo-form”>
        <input type=”text” name=”title”>
        <textarea name=”description”></textarea>
        <button type=”submit”>Submit</button>
    </form>
</template>  

Then in todo.js file we need to configure our form submit event:

Template.todo.helpers({  
    todos: function () {
        return Todo.find({});
    }
});

Template.todo.events({  
    'submit #todo-form': function (e, tmpl) {
        e.preventDefault();
        var title = tmpl.$('[name=title]').val();
        var description = tmpl.$([name=description]).val();
        if (title && description) {
            Todo.insert({title: title, description: description});
        }
    }
});

Ok, we have here some of the core concepts of event handling in Meteor. The event function takes two parameters, one is an event and the second is the template instance. We can find our input and text area by searching only in the template using standard jQuery functions. Then we will call the insert function on our collection. When it is done, our list will update automatically. You don't have to worry about syncing your data. Meteor will do it for you.

That’s it. In a couple lines of code you've got your backend and front end app. You can store your todo items in the database and you can list them all on the page. This is really powerful and simple with Meteor.

One more thing here. MongoDB is auto configured for that one instance of your app. You don't need to do it by yourself. This is a really cool feature too. Even when you want to deploy your app on Meteor servers you don't have to think about your database. It will be created automatically on the server too.

Hmmmm, ok cool, but this is a little bit strange... what about data security?

This is a very important part and I think it could be a topic for some other articles. Meteor is well prepared and your data could be secured with some additional work. Meteor provides some of the mechanism. One is server side method: https://www.meteor.com/try/9 there are also publish/subscribe data operations: https://www.meteor.com/try/10 You can also check 'allow and deny' for collections: http://docs.meteor.com/#/full/allow

These mechanisms are sufficient to protect your data. You should definitely read more about it after you gain more knowledge of Meteor.

Deploy your app for free with one command

This is for sure one of the strengths of Meteor as a programming platform. When you are ready with your app you can deploy it on the Meteor Galaxy servers using only one command which is:

$ DEPLOY_HOSTNAME=galaxy.meteor.com meteor deploy myAppName.meteor.com

Of course you need to have Galaxy account. That’s all that you need to do. You'll find very rich documentation after you log in to the Galaxy admin panel.

Deployment can be done on other commercial services like Modulus, Heroku or DigitalOcean.

There is also a good tool called Meteor Up You can use it when you want to deploy on DigitalOcean, for example. It is very simple to configure.

Hybrid Apps with Meteor

Meteor is also a platform for writing hybrid (Cordova) apps. If you are not familiar with Cordova apps, go and read about them. You will be able to write mobile apps using only web technologies like html, css and javascript and with Meteor it is even simpler. You will be able to use Meteor reactivity to sync your data on mobile devices.

Like in the case of deployment here you will install Android or iOS SDK with one command. Also you can run your Android or iOS emulator with one command. To install SDKs you should run:

$ meteor add-platform ios

and for the Android device:

$ meteor add-platform android

This is that simple. Then you can run your emulator by:

$ meteor run android
$ meteor run ios

I think the best article on this topic in the context of Meteor is the one from Stephan Hochhaus. I strongly recommend it if you want to write your first mobile app with Meteor. Also you can read an article about this topic: http://guide.meteor.com/mobile.html

Ending thoughts

If you want to build your full app with backend programming and database or even transform it into a mobile app and deploy it, but you don't want to spend much time on configuring your environments etc., Meteor will be the best choice for you.

It is also great for front-end tasks because you don't need to do any configuration. It is light and you can integrate it with Angular, React, or whatever you want. This is not such a particular framework.

It is good to know that Meteor is well founded and the community is great too.
You can find all those people here: http://forums.meteor.com and here: http://crater.io

There are many awesome tools in package registry on Atmosphere: https://atmospherejs.com

You can also use Scotty – the Meteor boilerplate used as an example in this article: https://github.com/juliancwirko/scotty

Where to start learning?

You should definitely look into these materials:

Let me know what topics about Meteor you want to see here in a more detailed way. You can use the comments below or you can send me an e-mail. Thanks!

Comments

comments powered by Disqus