Thursday, May 30, 2013

Quick Links - May 30 2013 - Static Site Generator in node.js and CoffeeScript

Hey All,

Just a couple of quick links today, the first is a static site generator in CoffeeScript running on node.js and the second is a bit of an introduction to static site generators.  Perhaps these links should be presented in the opposite order but no, I'm just crazy like that.


Enjoy!

Thursday, May 16, 2013

Quick Links - May 16 2013 Interesting JavaScript Trick

Hey All,

Just one quick link for the day but it's a neat one.  Didn't realize this was possible in JavaScript.  The title doesn't really describe the article, basically it's a way to convert a comment to code:


Cool stuff indeed.  Hoping to get a few more posts up in the next little bit, working on a side project right now that is taking up most of my time but with a long weekend coming up maybe some time will free itself up.

Enjoy

Tuesday, May 7, 2013

Backbone.js Single Page Application Template for .NET MVC4

Hey All,

asp.net is hosting a Single Page Application(SPA) Template for Backbone.js.  As a .NET developer and a fan of Backbone.js this looks to be a great resource.  Haven't had a chance to try it out myself yet on anything, hoping maybe this weekend to do a small app with it.

As a note, it uses TypeScript files for it's client side code.  TypeScript is a bit like CoffeeScript in that it compiles down to JavaScript but unlike CoffeeScript which comes with it's own syntax, TypeScript is more of a super set of JavaScript.  I'll likely do a little overview of TypeScript soon to show what it's all about.

Here is the template code of github.

Enjoy.

Wednesday, April 17, 2013

Quick Links - April 17 2013 C# Intro

Hey All,

Two quick links for the day both from the same author.


The posts serve as an introduction to C# for experienced developers of other languages such as C or Java .  Good stuff in here and can be used as a simple C# reference as well.

Enjoy!

Thursday, April 11, 2013

Coffeemarklet - A Neat Little Web App for Developing Bookmarklets in Coffeescript

Coffeemarklet - A Neat Little Web App for Developing Bookmarklets in Coffeescript

Here's a neat little web app for developing bookmarklets in Coffeescript.  It's not really a fully featured development environment or anything but it does the job.

Just enter some CoffeeScript into the text box, click Generate Bookmarklet and your done.  Has an option to include jQuery as well which is a convenient feature.

I've been looking to add bookmarklets as part of a couple of projects so this was a really good find for me.

Enjoy!

Wednesday, April 10, 2013

Quick Links - April 10 2013 Coffeescript and Backbone.js

Hey figured I better put a post up since I've been slacking lately.  Here's a couple of interesting finds:


The first post is a discussion on using Mixins with Coffeescript as well as a couple of example implementations.
The second is a presentation on Coffeescript vs Typescript highlighting some of the differences and similarties, pros v cons, etc.  I added this as I hope to begin using TypeScript on some pet projects and plan on doing a post on it soon.
The third are some backbone tutorials, mostly simple stuff but some interesting none the less, looking to up the Backbone.js content on here so I figured this would be a good start.

Have a post coming on using Backbone.js sync soon, showing how to interact with RESTful web service from Backbone.

Enjoy!

Wednesday, March 13, 2013

Quick Links - March 13 2013 More Literate Coffeescript and 2000 C# Things

Hey all a couple of interesting finds for the day:

The first link is a blog post from Jeremy Ashkenas about Literate Coffeescript.  Why it was added to the project and what he hopes it will help accomplish.  It also discusses briefly and links to a blog platform written in Literate Coffeescript called Journo.  If you are interested in Literate Coffeescript I highly recommend reading the post and reviewing the source.

The second is a blog I've been following for a bit and have been reading through frequently as of late, 2000 Things You Should Know About C#.  He's not quite at 2000 things yet but Sean Sexton has some great little nuggets of information on this blog.  There's quit a bit of simple and straight forward stuff here but it's great for reviewing C# concepts and ideas.

Thursday, March 7, 2013

Source Maps in Coffeescript 1.6.1

Source Maps in Coffeescript 1.6.1

As a follow up to my previous post on the subject, I'm pleased to let my readers know that source maps are now available in Coffeescript 1.6.1 and up.

This is a big step forward in debugging for Coffeescript.   To create a source map along with your compiled javascript, simply use the --map or -m option when compiling.   Currently,  Chrome and nightly WebKit builds are the only browsers to support source maps.  To enanble source maps, open the developer tools in Chrome and click on the gear icon in the lower right corner, this will give you the settings dialog.  In settings set "Enable Source Maps" to on(checked).

Source maps are also available for Node.js.  For more information on Node source maps please see this post.

For more infomation on source maps, see this HTML5 Rocks tutorial.

Monday, February 25, 2013

Quick Links - February 25 2013 Coffeescript and Web Essentials

Hey all a couple of interesting finds for the day:

The first link is to the change log for Coffeescript which is up to v 1.5.  I usually don't post about version changes but in this particular update they have added literate programming features, which I'm not overly familiar with but seems really cool.

The second is a link talking about Web Essentials 2012.2.  I took a Microsoft course over the weekend and it inspired me to drop that here.

Enjoy

Thursday, February 21, 2013

Coffeescript And Backbone.js - Convert Reminders App

Coffeescript And Backbone.js - Convert Reminders App

Hey all,

Gonna be a bit late on the post regarding callbacks in javascript.  Ran into a little time consuming issue while updating my gift list app and haven't had time to work promises into it yet.  That should be on it's way soon but as Space Hog would say "In the mean timeeeeee"... More Coffeescript, this time with some Backbone.js.

I've been meaing to change my Messages and Reminders app from vanilla javascript and jQuery to something in Coffeescript, Backbone.js and jQuery(w/UI).  Why you ask?  Well the app is essentially a single page web app already and though the initial version is working fine from the front-end perspective right now, some recent changes I wanted to add showed an increasing need for a bit more organization and robustness in the code so...

If you haven't seen Messages and Reminders, check it out, sign up, play around with it, a new version should be out before the end of the month.  So basically we have a web app that allows you to send messages back and forth between yourself and other members as well as add reminders to yourself or convert a message to a reminder.  Pretty simple stuff.  Lets take a look at some of the code:


class Message extends Backbone.Model 
  defaults: 
    to : "Me" 
    from : "You" 
    title : "Hey" 
    body : "What's up" 
    date : "02/18/2013"

Models are the basic building blocks of Backbone.js.  Here we are creating a Message class which will extend the base model class and then we add some defaults to that new class.  By extending the model class we get all kinds of great utility methods including a getter and setter for our properties and other great methods.  The defaults shown here are the default values of our model properties if we instantiate an instance and don't set the properties at that time.

If we do this


newMessage = new Message() 
newMessage.to ## 'To'

or if we do this


newMesage = new Message({to: 'You'})
newMessage.to ## 'You'


Ok, hope that is clear as mud.
Next we are going to setup a collection which will hold our models


class MailBox extends Backbone.Collection

Wow is that it for a collection? Yup. Actually for the purposes of this article we could even write

reminders = new Backbone.Collection()

So why extend if we could just instantiate a new instace of a collection. Mostly for future issues including adding some error checking on the collection.
Something I should mention just occured to me while discussing collections. Backbone has one hard dependency, either Underscore.js or lo-dash. Both do essentially the same thing, lo-dash is smaller and faster whereas Underscore is larger but maintains some support for older browsers. Either will work. The reason for my sudden memory flash of Undercore is that Backbone proxies 28 iteration functions to collections such as forEach, map, reduce, min, max and more. This makes collections super useful in any data heavy web app. I should note that collections are not the only reason Underscore is a requirement for Backbone so don't assume just because you are not planning on using the iteration functions you won't have to include Underscore.


Next up we get into some views


class MessageView extends Backbone.View 
  tagName: "li" 
  className: "message" 
   model: Message 
   temp: "
      <%=to%>
      <%=from%>
      <%=title%>
      <%=body%>
      <%=date%>
   " 
 initialize:() => 
   @render() 
 render: () => 
 if @temp? && @model? 
   messageTmp = _.template(@temp) 
   @$el.append(messageTmp(@model.attributes)) 
 return @


Views are what we use to display data in a Backbone app.  They can reflect a model, collection or just a be a static representation of whatever you want.  Here we have the view that is created when a new Message model is added to a MailBox collection.  A few things to note about the view.  I am using the tagName and className properties to describe what type of element I want created, so a list element with a class of message.  The temp property is actually a template string that we will compile down and use to display the model data.  Here we are using Underscore templates but we could use whatever templating we wanted.  Then we have the initialize function which is our constructor, this function is called when you create a new instance of your model so whatever setup needs to be done do it here.  In this case I am simply calling into the render function.  The render function's default implementation is a no-op, it's provided to be overridden to contain whatever needs to be done to get your view properly rendered.  So in this render we compile our template down and send in @model.attributes which is a property provided that cotains the model data as a hash or in this case {to:"To", from: "From", title: "Title"..etc}.  We then append the string to the views @$el which is a wrapper function that uses jQuery or Zepto if they are available on @el which is the current element.  We then return @ (javascripts this) which is a common practice to allow method chaining.  Why did we call render from initalize, just cause.  It basically lets me simplify the calling code from new MessageView({model:model}).render() to new MessageView({model:model}).


class MailBoxView extends Backbone.View 
  tagName : "ul" 
  className : "mail-box" 
  initialize:() => 
    @listenTo(@collection, "add", @render) 
  render: () => 
    if @collection? && @collection.length 
      newMessage = @collection.at(@collection.length - 1) 
      @$el.append(new MessageView(model:newMessage).el) 
    return @

This is the code for the MailBox collection view.  Notice in the initialize function(or constructor) we call @listenTo(@collection, "add", @render).  listenTo is from Backbone events.  It takes a collection or model, an event type and a function.  When the listening event type is fired by the collection or model the callback function executes.  So here, when a model is added to the views collection, we execute the render function of the view.  So where does this collection come from? Look further down the code to the MailBoxView instansiation reminderView = new MailBoxView(collection: reminders).  We add the collection reminders here to the new MailBoxView.  Why not add the collection as a property?  De-coupling.  We don't want this particular collection tied to the view in that way, we want the backbone events to do what they are there for which at least in part is helping our different application pieces communicate.  There is way more on events in the Backbone documentation, you can even create and use custom events which can be extremely useful.


class CreateMessageView extends Backbone.View 
  events: "click .submit": "addMessage" 
  addMessage: () => 
    to = @$el.find(".to").val() 
    from = @$el.find(".from").val() 
    title = @$el.find(".title").val() 
    body = @$el.find(".body").val() 
    date = @$el.find(".date").val() 
  newMessage = new Message( 
    to: to from: 
    from title: 
    title body: 
    body 
    date: date 
  ) 
  @collection.add(newMessage) 
  @render() 
  return 
 render: () => 
   @$el.find("input:not(button)").val("") 
   return @ 
 initialize: () =>

Alright! More events!  Here we are adding the events using the events property on the view.  This is a form of event delegation which you may also be familar with from jQuery, which would look like $("#createMessage").on("click", ".submit", @addMessage).  Event delegation speeds up events by having the event bubble only as far as the containing element.  A problem with delegation in Backbone is that if the object is destroyed without properly removing the event binding first, you can create a memory leak[citation needed].  So keep that in mind.  Now back to what's going on here.  On clicking the submit button we call addMessage which get's the values of the input fields and creates a new message (newMessage) of the type Message with the field values.  We then add the new model to the collection, which remeber will cause the MailBox view to render the new Message in it's ul element because it is listening for changes in this collection.  So where is the "#createMessage" element from?  Well we bind that directly to an existing DOM element that was rendered when the page was created

createView = new CreateMessageView( 
 collection: reminders 
 el: document.getElementById("createMessage") 
 )

Notice again the collection being set to reminders and here we see that el is explicitly bound to the DOM element instead of creating an element to insert data into.


reminderView = new MailBoxView( 
 collection: reminders 
 ) 
$("#reminder").append(reminderView.el)

The final line ties it together by creating the reminder view and attaching it to the DOM at the "#reminder" element.

You can see the code here

That was a bit long for the type of overview I wanted to do but I think I covered the basics.  Next time I talk at length about Coffeescript I'm hoping to do some routing and show some use of Backbone.sync.

Wednesday, February 13, 2013

Quick Links - February 13 2013

A few more quicklinks for the day:

The first two are Coffeescript related, first is another Coffeescript book, this one has interactive features and the second is a cheat sheet reference for Coffeescript.

The second is under the javascript heading but could also apply to Coffeescript, it's a discussion on context binding, which if you've done any amount of front-end work you've had issues with, which are discussed here.

Tuesday, February 12, 2013

Quick Links - February 12 2013

A couple of free on-line Coffeescript books:

The first has a new updated paid version available but it's still very usefull as a simple introduction or quick reference.  The second is longer and more in depth from a conceptual perspective.  Both worth a read.

Monday, February 11, 2013

Quick Links - February 11 2013

A couple of good reads:

The first is more info about source maps as dicsussed in my earlier post.  The second is a good write up on how to write optimized javascript.

Along the lines of javascript and more specifically node.js, I"m hoping to have a post up later in the week about promises in node and how they can help get you out of call back hell.

Friday, February 8, 2013

Quick Links - February 8 2013

Just a couple of good reads I found today:

Both are related to the pub/sub observer pattern found often in event implemenations.  Anyone who's had to implement their own pub/sub system knows it comes with some issues, which both discuss and search for answers to.

Wednesday, February 6, 2013

Oh yeah, Coffeescript (Redux)

List Comprehensions

In my previous post on Coffeescript I stated that during my initial impression I noted that there were some "structural changes" to the ways loops were formatted.  That's not really the best way to state it.  In Coffeescript most loops are actually List Comprehesions.

List comprehensions are based on the mathmatical set builder notation, check the Wikipedia article for the specifics but the basics are

result = (func x for x in [0..20] where x%2 == 0)

That basically breaks down to give me the result of calling func x on the set, x is 0 to 20 where x mod 2 is even.  Seemed a bit complicated to me at first but it's really quite a powerful tool.

First all loops are based on this so a simple loop from 0 to x is


for i in [0..x]

Pretty simple, it also helps clear up the forEach on objects or lack there of in current javascript

output = ""

obj = 
 prop1: "hello ", 
 prop2: "world"

for i, prop of obj 
 output += prop 

console.log(output) ## hello world

Note here the use of the "of" keyword this is used to signal that we are iterating over an object and not an array.  You can also avoid any properties that may be inherited from the prototype by added the "own" keyword


obj = 
 prop1: "hello ", 
 prop2: "world"

for own i, prop of obj
 output += prop 

console.log(output) ## hello world


Here's an excellent example of the usefulness of list comprehensions:

square = (x) -> x * x 
results = (square x for x in [0..20] when x%2 == 0) 
console.log(results) ##[0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

Wasn't that super useful!  Ok, not so much, but what you should take away is that this basically gives you native forEach(as stated earlier), map, filter/select functionality which is really convenient when dealing with data or even the DOM.

Source Maps

In my first post about Coffeescript I mentioned that when I first approached the language the fact that it compiled down to javascript that would have to be debugged was a big drawback in my eyes.  The thought being that having to determine what javascript was associated with what Coffeescript was simply an annoying extra step in debugging.  This isn't really the case in practice and now not an issue at all because of Source Maps.

Source Maps are available in Chrome, hopefully Firefox soon and someday Internet Explorer.  They are not a feature specifically of Coffeescript.  The idea is that a source map is used to map output javascript back to the compiled language in this case Coffeescript.  So opening your dev tools you would be able to see the original Coffeescript, set breakpoints and have errors that would point back to the line in the original Coffeescript.  Pretty cool eh.  As I said this isn't a feature of the Coffeescript language but the browser or other dev tools.  JQuery as of v.1.9 have source maps available from the minified version back to development version.  Source maps for the main Coffeescript project are currently kind of up in the air but... Coffeescript Redux a re-write of the original compiler which aims to maintain the language structure but add some optimizations, have added support for source maps to Coffeescript.

Source maps can help remove a layer of complexity some people may see with Coffeescript development.  For more on source maps check it here.

Update: Source maps are now available in Coffeescript, please see this post for more information.

Tuesday, January 29, 2013

Oh yeah, Coffeescript

Oh yeah,

One thing I forgot to mention picking up over the last year was Coffeescript.

When I first heard about Coffeescript I was interested.  After checking it out initally I came away rather unimpressed.  It added a more traditional looking class structure for OOP, had some structural changes to loops and conditions but in the end since it compiled down to Javascript and you would be debugging that code, I didn't see the point.

Some time later I decided to give it a shot on a new project and once I started using Coffeescript, I was sold.  I now use Coffeescript on pretty much all projects.  Why?  Once I began to do some real development in Coffeescript I noticed that I was able to work much faster in it than Javascript alone.  The class structure I dismissed early on does come with some features that make it easier in many cases to develop faster.  Simple inheritance with extends and the fat arrow for context binding allows you to code faster without having to dedicate as much time to boilerplate code.

Classes

Javascript doesn't have classes.  It uses a prototypical system for inheritance and everythis is declared using functions.


function A()


}

var a = new A(); 
console.log(a instanceof A); // true

The above code says that instance a has the constructor of A in it's prototype chain and will contain it's properties and methods.

Too add properties and methods we

A.prototype.info = "On the prototype";

A.prototype.hotMethod = function(){ 
 return "this method is hot"; 
};

console.log(a.info); // On the prototype
console.log(a.hotMethod()); // this method is hot

When we get to inheritance that's where it get's hairy for many people, myself included

function B(){

}

B.prototype = new A(); 

B.prototype.newHotMethod = function(){ 
 return "this method is the new hotness" 
};

var b = new B(); 
console.log(b instanceof B); // true
console.log(b.hotMethod()); // this method is hot
console.log(b.newHotMethod()); // this method is the new hotness

There are better more thorough ways of doing inheritance in javascript but that will work.

Here is the same basic class setup in Coffeescript

class A 

 constructor: () -> 
 info: "this is on A" 
 hotMethod: () -> "this method is hot" 

a = new A();
console.log(a instanceof A) // true 
console.log(a.info) // this is on A 
console.log(a.hotMethod()) // this method is hot

And basic inheritance

class B extends A 
 constructor: () -> 
 newHotMethod: () -> "this method is the new hotness" 
 b = new B();

console.log(b instanceof B) // true
console.log(b.info) // this is on A 
console.log(b.hotMethod()) //this method is hot 
console.log(b.newHotMethod()) //this method is the new hotness

As you can see the Coffeescript is slightly less verbose and more easily readable, which can make it both faster to code and easier to maintain.

The Fat Arrow

Not simply a gluttonous arrow, fat arrow notation has actually worked it's way into a future version of Javascript.  Using this keyword is javascript can lead to some gotchas, such as the following:

function App(){ 
 this.something = "something!"

 var theClick = function(evt){ 
   console.log(this); // the button that emited the event
   console.log(this.something); //undefined 
 }; 

 this.notTheClick = function(){ 
   console.log(this.something); // something! 
 }; 

 $("#clickit").on("click", theClick); 
 this.notTheClick(); //something


run = new App();

That is a totally contrived, non-sense example of scope issues in javascript (featuring jQuery) but it does prove the point. The context for the event handler is different from the enclosing App function but on visual inspection that is difficult to tell. In Coffeescript we have the fat and skinny arrows for context resolution

class App constructor: () -> 
   $("#clickit").on("click", @fatArrowHotness) 
 fatArrowHotness: () => ##binds it to the instance of App
   console.log(@) // context is App instance 

 runApp = new App()

One thing you'll notice here is my use of the @ symbol which is an alias for this in Coffeescript. As promised, using the fat arrow has bound the context of fatArrowHotness to the instance of App, if you use a skinny arrow the context would be the DOM element that emitted the click event.

class App 
 constructor: () -> 
   $("#clickit").on("click", @thinArrowHotness) 
 thinArrowHotness: () -> 
   console.log(@) // the DOM element that was clicked 

 runApp = new App()

The fat arrow makes scope resolution far easier to see at a glance which again can lead to faster development and easier maintanence.

These are just a couple of reasons I have been using Coffeescript so heavily over the last little bit, I hope to share more of why I enjoy Coffeescript in the next little bit.

Monday, January 28, 2013

Back to Bring the Info

Hey all


I'm back to continue my blogging adventures after quite awhile off.  I haven't had time to keep up with the blog as work/life was keeping my quite busy and although I'm still quite as buy, I've decided it's time to get back to doing some blogging.

First off I want to review some of the topics I was discussing in earlier posts.  I didn't get my last effort with go and backbone.js off the ground.  I've been keeping up with both projects, especially backbone as I was doing some extensive front end work over the last year or so.  I've fallen off using go as a primary development language but that doesn't mean that I didn't like it, I actually think it is quite good for rapid development.  I was working primarily in .Net with MVC in a windows environment so it didn't give much time for developing with go.

More on the .Net stuff in a bit but first I want to review what has been going on with go and talk a bit about where I would like to go with it (I don't think I intended a pun but there it is anyway).  Since my last writing go has gone version 1.  Even though I haven't been using a lot of go I have been trying to keep up with it and the go ecosystem seems quite healthy.  Sometime in the next few weeks I'd like to tackle a new go project on app engine, using the web.goRevel framework or possibly just use the Gorilla tools with some home baked http stuff.  Web.go used to be the only way to go but I'm not sure how the project support is going these days.  Revel is pretty new and interesting.  I'm also hearing lots of good things about using Gorilla with the go library http package so we'll see, maybe end up doing something for all three.

The backbone.js community has really taken off since my last posts about it.  There are many great tutorials out though as well a large list of plugins and just a great on-line presence in general.  I'm not going to go over any specifics here as I will be doing some backbone stuff for sure here in the next few weeks.

Now a little on some projects I have been working on.  Over the holidays (actually sometime before) I started developing a project in node.js.  I had left one job and was waiting for another to start so I had some time on my hands and wanted to see what all the fuss was about.  The project used node.js with a mongodb database and had facebook and twitter integration.  The app was a simple gift list which basically allowed you to add  wish list items your facebook and twitter friends could see.  There is more to it but it's incomplete (of course) and I'm still working on getting it out for sometime this year.  I did enjoy developing in node.js.  I have been doing front end development with javascript for years so I was quite familiar with it going into this.  One major problem I had earlier on with the development of the project was "call back hell", I'm hoping to share some techniques to overcome this soon.  Working with the noSQL mongodb was interesting and I enjoyed that as well.  The noSQL db's are something I also hope to share some thoughts on soon.

As I mentioned earlier I have been primarily developing in .Net MVC for the last year and a half or so.  One project I have been working on and is in "early alpha" state is messages and reminders.  Feel free to follow the link and sign up to see what it is and what it does.  Again it's a very early version and has many features that will be added in the next release (early next month, fingers crossed) but I have been using the current version for simple reminders and messaging between a few friends.  It also uses twitter bootstrap as it's base CSS. As primarily a developer I'm a huge fan of bootstrap.  I'm hoping to go over bootstrap soon as well as customizing it with LESS.  The long term goal is to have the web app as well as a native iOS, Android, Win8 and maybe BB10 apps as well.  I`m looking at using the base HTML5 and compiling to the other platforms using a tool such as appMobi or Phonegap, so look forward to that.

Lastly, as stated earlier, I left one job for another recently and the direction of development I`ll be doing has changed extensively as I`ve gone from primarily app development in HTML and Flash to a more Business Intelligence path so I`ll be sharing my thoughts on that as well.

Anywho, that was quite a rant, so TLDR; I`m back and hoping there are still some people out there reading.

Jason