Category: JavaScript

JavaScript

Podcast Episode 33 – Rob Eisenberg on Aurelia.js

Rob EisenbergLast Monday, Rob Eisenberg released Aurelia.js. This was a culmination of sorts of a whirlwind of activity that was kicked off when Rob left the Angular 2.0 team at Google. A lot of people wondered what he was up to (including me!), so I asked him to be on the show to talk about what’s been going on. We talk about SPAs, why he left Google, what’s special about Aurelia, how to handle learning all of these frameworks, and much more.


Links Mentioned in this Show:
Aurelia
Rob’s Leaving Angular Post
Rob’s Twitter
Rob’s Blog
Aurelia vs Angular Round One

You can also subscribe to the podcast at any of these places:
iTunes Link RSS Feed

Thanks to all the people who listen, and a special thanks to those who have rated me. I really appreciate it.

The episodes have been archived. Click Here to see the archive page.

Hood.ie

Hoodie, Part 2 – Our First Custom Hoodie

Last time, we got Hoodie installed and made the first simple application. If you had done it correctly, you would have been able to add ToDo’s and then remove them by clicking them. Let’s make another application, and while Hoodie supports templates to create applications, I’m just going to have it make the default application again and we’ll replace what we don’t need.

I’m going to type hoodie new part2 and create a new application called part2. Here is the result:

Our new part2 app

If we do issue a cd part2 command, we end up inside the application folder. Let’s take a look at what file are contained in the folder by default.

  • README.md – Contains information about the application, how to get started, and even how to deploy the application
  • package.json – As you can probably tell by the installation process we had to follow last time, Hoodie applications are really just Node.js applications and Node.js apps need a package.json file. We get the name of the app here as well as the list of dependencies that it needs to keep up to date and deploy.
  • node_modules folder – Another fairly self-explanatory one. This folder is where npm actually keeps the files needed for the application. If this was regular Node.js application, we might just get the package.json file from source, and need to call npm install in order to get this folder and its contents, but the hoodie new command did that
  • data folder – This folder is our database. You actually won’t see it the first time, but instead it is created the first time you run hoodie start. If you want to easily wipe out everything for the app, renaming or deleting this folder will cause a brand new database to be created.
  • www folder – Everything for the application, asset-wise, is here. All HTML, CSS, JS, images, etc live in this folder. Treat this like any other web root, Hoodie doesn’t do anything to new files in here that would cause you to lose your work.

I’m going to leave the application intact and we are going to just make a new file inside for our demonstration. All we really need to make the HTML file we are creating “hoodie-able” is to include this script:

<script src="/_api/_files/hoodie.js"><script>

If you go digging around our directory, you aren’t going to find that file at all. The reason is because the Hoodie server serves that file up dynamically by itself. Not only is the goodness of Hoodie in this file, but it also has the front-end code required to work with any of the plugins that you’ve installed along with the app.

The first thing I’m going to do is add a new file in the /www directory called new_user.html. Here are the contents of that file:

I’m also going to create a new file in the /www/assets/js directory called new_user.js. Here are the contents of that file:

The HTML file should be pretty self explanatory. I just made a simple form that takes an email and a password. We include the hoodie script file and our own script file and jQuery. If you call hoodie start and give it a password for the application (first time only), you will get the default screen that we had before.

Our JS file shouldn’t need too much explanation, but there are some things that are likely new to you. The “use strict” is something new in ECMAScript v5 and it forces you to write better javascript. Here is some documentation if you are curious. The next line “var hoodie = new Hoodie();” instantiates the Hoodie object.

After that, we have a block of code that is wrapped inside of the jQuery document ready method. Much of the code is concerned with trapping variables and manipulating the screen, but we should be interested in the two lines that are “Hoodie-centric”.

hoodie.account.signUp(username, password).done(function (user) {checkUser();});

hoodie.account.signOut().done(function (user) {checkUser();});

Our hoodie variable that we declared earlier has an account property that accesses the account store inside of the CouchDB instance. Account has signUp(), signIn(), signOut(), changeUsername(), resetPassword(), and changePassword() methods that you can call. The signUp() and signOut() methods also allow you to provide a callback, which we did and used to manipulate the DOM. All very simple and basic, which is definitely what the Hoodie developers were trying to accomplish.

If you now go to http://127.0.0.1:6007/new_user.html (your port could vary, check the console as you start), you will see a screen like this:

Hoodie Part 2 New User Form
(ignore the symbols in the textboxes to the right, that is LastPass being helpful)

When I put in an email and password, and click register, I get logged in and greeted.

Our Filled-In Form

Signed In

Clicking Sign out gets us back to where we were:

Signed Out

So, what did we do? Did we really just create an account? Go back to the main page, for me that is http://127.0.0.1:6007, and go to the upper right hand corner, hit the drop down arrow and choose to sign in.

Main Page Sign In Button

You will be presented with a form. Put in the information that you registered with on our page.

Main Page Sign In

You will now be shown as signed in. We really did create an account.

Main Page Sign In Successful

That’s it for this time. Next time, we’ll try creating some custom objects and see how easy (or hard) that is with Hoodie.

Hood.ie

Hoodie, Part 1 – An Intro to Hoodie

HoodieSome time ago, I was browsing Reddit or Hacker News and I came across a link to something called Hoodie. Of course, that’s an appropriate sounding programmer framework name, but what is it? In their own words, “Hoodie enables you to express yourself through technology by making web app development very fast, easy and accessible. It’s a complete backend for your apps: develop your frontend code, plug it into our API and your app is ready”.

Well, doesn’t that sound convenient? But, who is it for? Quoting their site again, they say, “Currently, Hoodie is mainly for frontend developers who want to build their own applications based on it, and for Node.js developers who want to help us extend Hoodie’s core by building plugins. Hoodie’s future goal is to be accessible for designers and people with few coding skills because we think this matters”.

Okay, well right away, some of you might lose interest because you aren’t designers and you would probably be offended if you were described as having “few coding skills”. However, I do agree with the Hood.ie team and it does seem that web development is still somewhat of a matter of privilege. I wrote a post back in May, 2013 called How Deep is the Rabbit Hole. In the post, I took issue with another blogger who was complaining about all of the things that developers had to know in order to be viable developers.

I still hold to my stance. I believe professional developers can get by knowing a few things, but as they are in the game for awhile, they will learn more and more about their craft. There is no shame in that. At the same time, if someone wants to build a simple functional application, should they have to learn the entire full stack of development – soup to nuts? We aren’t talking about “Enterprise Class™” code here. I’m talking about someone who wants to build a simple application who only knows the basics of Web UI from a design perspective. That’s who Hoodie serves and who my audience is for this series.

At the same time, if you are more of a full stack developer, it doesn’t hurt you to learn more about other tools either. While you may see Hoodie to Web Apps what Access is to Databases, that doesn’t mean that the tool doesn’t have an audience and it doesn’t mean that it hurts to have it in your tool belt to offer as potential solutions to clients or to friends.

So, how do you get started with Hoodie? First, you need to have the following prerequisites installed:

  • Git
  • CouchDB
  • Node.js & NPM

You can find out how to best install those for Windows, Mac, or Linux over here.

Once you have those items installed, you can just install Hoodie from the command line by typing the following:

npm install -g hoodie-cli

That’s all there is to it. You can verify that you have installed it correctly by just calling hoodie from the command line and verifying that you see output like I have here:

A successful Hoodie installation

From there, you can begin to use Hoodie by calling hoodie and passing in an application name to create. For my purposes, I’m going to create a new application called pos_example by executing the following command

hoodie new pos_example

Hoodie App Created

Doing as it suggests, once I cd into the directory and call hoodie start, I get this output.

Peters-iMac:~ pshearer$ cd pos_example/
Peters-iMac:pos_example pshearer$ hoodie start

.d$b.  .d$b.  .d$$$$$$b.    .d$$$$$$b.  .d$$$$$$b.  .d$b..d$$$$$$$$b.
$$$$$..$$$$$.$$$$$$$$$$$b .$$$$$$$$$$$b $$$$$$$$$$b $$$$$$$$$$$$$$$P'
$$$$$$$$$$$$d$$$$$$$$$$$$bd$$$$$$$$$$$$b$$$$$$$$$$$b$$$$$$$$$$$$$$$b.
$$$$$$$$$$$$Q$$$$$$$$$$$$PQ$$$$$$$$$$$$P$$$$$$$$$$$P$$$$$$$$$$$$$$$P'
$$$$$´`$$$$$'$$$$$$$$$$$$''$$$$$$$$$$$$'$$$$$$$$$$P $$$$$$$$$$$$$$$b.
'Q$P'  'Q$P'  'Q$$$$$$P'    'Q$$$$$$P'  'Q$$$$$$$P  'Q$P''Q$$$$$$$$P'

Version: 0.6.3 (node v0.10.33, npm 2.1.10, platform: darwin)

Initializing...
CouchDB started: http://127.0.0.1:6003
Waiting for CouchDB [---*--] SUCCESS 
prompt: Please set an admin password :  
WWW:    http://127.0.0.1:6001
Admin:  http://127.0.0.1:6002
Starting Plugin: 'hoodie-plugin-appconfig'
Starting Plugin: 'hoodie-plugin-email'
Starting Plugin: 'hoodie-plugin-users'
All plugins started.

[hoodie] Hoodie app is running!

You’ll notice that I had to specify an admin password and also, automatically, my browser launched to http://127.0.0.1:6001, where I was greeted with this:

Hoodie Test Page

That’s it. As an introduction, we’ve gotten started with some generic scaffolding, but next time, we’ll look at how we can leverage Hoodie to make something a little more useful.

JavaScript

Examining Moment.js

Moment.jsRecently, I was listening to the .Net Rocks! Podcast and Miguel Castro was on talking about MVVM for the web. I only mildly care about the topic, but I like to listen to things even outside of my normal sphere of interest to broaden my range of knowledge. Another side benefit is that sometimes you get unexpected gold nuggets thrown your way. This was one of those times.

Miguel was talking about some JavaScript libraries that were popular with his circle of friends/peers and he mentioned Moment.js. I had heard the name come up in the list of all of the {{noun}}.js libraries that were out there, but never really paid it any mind. All the while, I was suffering JavaScript date pain and I didn’t have to! 😉

To get started using it, you can either download it from the link above, or you can use npm, NuGet, or bower to install it.

bower install moment --save # bower
npm install moment --save   # npm
Install-Package Moment.js   # NuGet

From there, you can just reference it into your web page. Alternatively, you can just reference it from a CD and never do the install (//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.js is one).

I’m starting out with this shell of a page. I made a div with the id of playground here I can write out output from Moment.js without using alerts all over the place. I’m going to wrap all of the calls to moment in the writeToPlayground method to get the output.

<html>
<head>
<title>Testing Moment.js</title>
</head>
<body>
<div id="playground"></div>

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.js"></script>
<script type="text/javascript">
function writeToPlayground(val) {
	document.getElementById('playground').innerHTML += val + '<br />';
}
</script>
</body>
</html>

I have this shell – including all of the code in this post – as a jsfiddle that you can access at http://jsfiddle.net/PeteOnSoftware/pe4n383h/ to help make it all as clear as possible.

To get started with moment, you just have to create a moment object and then call the format or calendar methods.

writeToPlayground("moment().format() returns " + moment().format());
writeToPlayground("moment().calendar() returns " + moment().calendar());

This gives us:
moment().format() returns 2014-11-15T08:32:47-05:00
moment().calendar() returns Today at 8:32 AM

The format method takes a format string and gives us a lot of power

writeToPlayground("moment().format('dddd') returns " + moment().format('dddd'));
writeToPlayground("moment().format('MMMM') returns " + moment().format('MMMM'));
writeToPlayground("moment().format('MM/DD/YYYY, hh:mm:ss') returns " + moment().format('MM/DD/YYYY, hh:mm:ss'));

This outputs:
moment().format(‘dddd’) returns Saturday
moment().format(‘MMMM’) returns November
moment().format(‘MM/DD/YYYY, hh:mm:ss’) returns 11/15/2014, 08:32:47

But, this isn’t just about date formatting. It also does a lot of date manipulation for you. If you need to subtract time from a date, you can write

writeToPlayground("moment().subtract(10, 'minutes').format('MM/DD/YYYY, hh:mm:ss') returns " + moment().subtract(10, 'minutes').format('MM/DD/YYYY, hh:mm:ss'));

And that outputs: moment().subtract(10, ‘minutes’).format(‘MM/DD/YYYY, hh:mm:ss’) returns 11/15/2014, 08:22:47

But, better than ALL of those things is this next little beauty. If you use .Net as a REST API, whether through WCF or through WebApi, you are probably going to be used to seeing dates returned like this: /Date(1198908717056-0700)/. This is some tainted version of a JS date that doesn’t quite conform to standards that other people are using. If you try to deserialize it in JS, it fails, with or without the -0700 part. The issue is that JSON doesn’t specify a date format, so Microsoft returns *kind of* what you’d need to parse the date. The 1198908717056 part is the number of milliseconds since the Epoch and the -0700 part is supposed to be the timezone offset. Here are some examples of what would happen if you tried to just naively parse what you got back, or if you tried to parse it after doing some manipulation.

writeToPlayground("Trying to parse that as a new Date('/Date(1198908717056-0700)/') gives back " + new Date('/Date(1198908717056-0700)/'));
writeToPlayground("Trying to parse that as a new Date(1198908717056-0700) gives back " + new Date(1198908717056-0700));
writeToPlayground("Trying to parse that as a Date without the -700 as Date(1198908717056) gives back " + new Date(1198908717056));

Gives us:
Trying to parse that as a new Date(‘/Date(1198908717056-0700)/’) gives back Invalid Date
Trying to parse that as a new Date(1198908717056-0700) gives back Sat Dec 29 2007 01:11:56 GMT-0500 (EST)
Trying to parse that as a Date without the -700 as Date(1198908717056) gives back Sat Dec 29 2007 01:11:57 GMT-0500

I’ve run into these same problems trying to parse those kinds of values in Android and iOS applications, too. Here, in the second example, JavaScript just does the subtraction first, which is why the second result is about a second behind the third result (700 milliseconds).

However, Moment.js just takes that .Net value returned and handles it like a champ.

writeToPlayground("moment(/Date(1198908717056-0700)/).format('LLLL') returns " + moment(/Date(1198908717056-0700)/).format('LLLL'));

Brings back: moment(/Date(1198908717056-0700)/).format(‘LLLL’) returns Saturday, December 29, 2007 1:11 AM

That just makes my day! If you want to know more about Moment.js, go check out its page and documentation here. If you just want to play around, go check out my JSFiddle and mess with my examples or just enter sample dates into the textbox and click the PARSE button to see what Moment.js will do with your input.

JavaScript

String Replace in JavaScript

Today, I had the need to do a String.Replace in JavaScript. I thought, “surely, this is an easily solved problem”. It turns out that I was both right and wrong.

A quick DuckDuckGo search brought back that I could do something like this:

var input = "I hate Fridays.  Fridays are the worst!";
var output = input.replace("Fridays", "Mondays");

I would expect the value of output to be “I hate Mondays. Mondays are the worst!”. But it isn’t. Instead, the value is “I hate Mondays. Fridays are the worst!”, because the replace method will only replace the first instance of the match.

The first solution that I found to this was to modify the code to use a regular expression, which the replace method also takes. All you have to do is include the RegEx and the “g” flag to make the replacement global. That would make the code look like this:

var input = "I hate Fridays.  Fridays are the worst!";
var output = input.replace(/Fridays/g, "Mondays");

This does give us the correct output of “I hate Mondays. Mondays are the worst!”, but if this were to be a reusable method or a pattern throughout an application, getting the correct RegEx can be tricky to debug or come back to later. Not everyone is a RegExpert. That’s why the next solution that I found was ingenious and was the one that I ended up going with.

In this code, you split the string on your “outgoing” string, and join it back together again with your “incoming” string. That would look like this:

var input = "I hate Fridays.  Fridays are the worst!";
var output = input.split("Fridays").join("Mondays");

That gives us our correct output of “I hate Mondays. Mondays are the worst!”. This method can be slower in some browsers (This JSPerf test has Split/Join as coming out ~40% slower in Chrome), but if you aren’t doing this several hundred times in a loop, I think the readability and maintainability of the Split/Join way makes this easy to do.