Using .LESS with Windows 8 HTML5 Applications

by bhayden
16. November 2012 22:41

I’ve been experimenting with Windows 8 and WinJS in particular, but one thing that I didn’t much care for was going back to plain old CSS files when styling my apps.  LESS is my CSS replacement of choice so I was curious if one could use it with Windows 8 HTML5 applications.  Turns out to be a ridiculously easy thing to accomplish (which is probably why I couldn’t find any good blog posts about it).  All you need to do is download the LESS javascript file and include it in the head of your default.html page in your application and everything just works!

Tags: , , , ,

JSLinq

by bhayden
3. October 2012 22:49

As part of an educational exercise for myself, I decided to create a library that “ports” one of my favorite features of the C# language to JavaScript.  I say “ports” because I didn’t try and emulate the syntax directly of LINQ (though with the new proposed fat arrow syntax this would be possible).  One of the things I miss most when working in other languages is the LINQ API.  While I know that there are other libraries that likely do this better (underscore) or already have it built in, I find the familiarity of .where, .first, .any, etc. to be like a nice warm blanket on a cold day.

The educational portion of this was two-fold, familiarize myself with Git and use Jasmine.  For the past couple of years in my day job I’ve been using Mercurial for source control and that spilled over into my personal projects as well.  It also helps that Bitbucketprovides  private repos for no cost. Still I felt it was high time I jumped on the Git train. 

I have one more operator to finish for JSLinq before I’d dub it feature complete (select) as I don’t have any plans to add and of the OrderBy functionality.  I debated for a while on whether to extend directly on the Array and Object prototypes or to instead wrap them in my own namespace and provide the functionality that way.  The latter is the safer way but I ultimately decided to go with the former because it feels more like LINQ to Objects to have them directly accessible as methods on every object or array.  One of the other design decisions I made was to include the methods on both the Array prototype and the Object prototype.

This decision came about because at first I was only going to apply the methods on arrays, but then I decided to add support objects after the fact.  I decided to keep them on arrays because the implementation on arrays felt cleaner to me then if I passed completely through to the Object methods which are not as clean to me.

All in all this was a fun little project that I initially thought I’d never use, but now I’m considering bringing it into some of my projects as I really do like the API that LINQ provides.  You can check out the source here.

Tags:

Fun with promises

by bhayden
16. September 2012 20:02

A friend of mine recently asked me to explain jQuery promises and how they tied in to AJAX calls and the differences between when, then and done.  I crafted up a fiddle to explain it all and then figured I’d post here.  Then I got hit by a truck.  No, seriously, I did.  At least the car I was driving got hit by a truck.  This post, however, isn’t about that.

Promises in jQuery are powerful and incredibly useful.  If you’ve been using any of jQuery’s built in AJAX methods then you’ve been using promises and might not even realized it.  The key to the implementation is the deferred object.  AJAX calls return to you the promise of the deferred object.  Simply put, a promise is jQuery’s way of telling you that it will do the work you asked and then let you know when it’s done.  The promise itself has a few key methods that you can utilize.

The first method is the done method.  The done method is a wrapper that the promise will use to call a function that you can pass it.  Done has a sibling method, fail. Fail is used when the promise is not fulfilled. In the case of an AJAX request this could be because the server could not be reached.  You’ve probably used these before with code similar to this:

   1:  $.getJSON("http://myserver/data").done(function(data) {
   2:       //Something interesting with the data
   3:  }).fail(function(data) {
   4:       //let the user know something went wrong
   5:  });

The true power of promises is unlocked when you move beyond the done and fail methods.  The when method allows you to chain together multiple promises and then interact with the results of all the promises after they are completed.

   1:  $.when(ajaxReq1, ajaxReq2, ajaxReq3).then(function(data) {
   2:       //data will contain the results of all the AJAX requests.
   3:  });

The key to remember when working with promises is the order that handlers will execute in.  First anything attached via done will be executed, after those are executed then any handlers attached via when and then will be executed.  Here’s the fiddle I mentioned at the beginning that highlights the execution of these events.

Of course this is all good when using built in functionality, but what if you want to work with promises on your own?  As you can see in the fiddle, it’s possible to create your own deferred objects and pass them around.  When working with your own deferreds your methods need to return the deferred’s promise.  Once your caller has the promise, they can then attach any done or then handlers.  It is then up to you either resolve the deferred or reject it, like this:

   1:  var test1 = function() {
   2:      var d = $.Deferred();
   3:      var f = function() {
   4:          var data = {
   5:              p1: "Hello",
   6:              p2: "World"
   7:          };
   8:          d.resolve(data);
   9:      };
  10:   
  11:      setTimeout(f, 1500);
  12:      return d.promise();
  13:  };
In this case I’ve only worried about resolving the deferred object, but you could just as easily fail it.  Using and understanding promises unlocks a powerful tool in your toolbelt.

Tags: ,

Powershell Search

by bhayden
26. July 2012 21:11

Over the past year I’ve spent more and more time in Powershell.  While I haven’t graduated to full fledged scripts yet, I’ve found myself using two commands quite often to find files and phrases in those files.  This often came up at Jenkon when I needed to find out which patch file added a database column or value. It’s already proved handy in my first week at Web MD.  The first command is Get-ChildItem, which functions a lot like the dir command with a few extra switches.  The two I use most often are –rec which will search recurisively through the directory you specify and –include to limit the type of files that I search.  A typical command:

   1:  Get-ChildItem c:\dev -rec -include *.cs, *.aspx

This will search through all the directories under the dev directory and then return any that end with cs or aspx extensions.  Alone this isn’t terribly useful, however when you combine it with Select-String command you get a nifty little file search, like this:

   1:  Get-ChildItem c:\dev -rec -include *.cs, *.aspx | Select-String -pattern Foo

By using a pipe (‘|’) Powershell will send the results of Get-ChildItem to the Select-String cmdlet (and this is where the *nix folks laugh and say that’s a long winded way to type grep), allowing you to search all the files for whatever phrase you’re looking for.

Of course doing the command as typed will print everything to the console.  Not terribly useful if you get a lot of results.  The final piece is to output the results to a file:

   1:  Get-ChildItem c:\dev -rec -include *.cs, *.aspx | Select-String -pattern Foo > bar.txt

Now you can browse the results in bar.txt.  It’s not as elegant as grep but it does get the job done!

Tags: ,

Exploring JavaScript Inheritance: The extend method

by bhayden
1. July 2012 22:16

In my previous post I gave an overview of some inheritance techniques I’ve begun using in recent projects.  In this post I’m going to explore one of the key pieces that finally clicked for me.

The extend method is a method that I added to my objects that allows me to take one object and then add properties to it to create a new object that contains the functionality of the base object and the new properties.  Here is the extend function again:

   1:  function(properties) {
   2:      var property, newObject;
   3:      newObject = Object.create(this);
   4:      for (property in properties) {
   5:          if (properties.hasOwnProperty(property)) {
   6:              newObject[property] = properties[property];
   7:          }
   8:      }
   9:      newObject.parent = this;
  10:      return newObject;
  11:  }

If you’re not familiar with Object.create then I suggest you read this article by Douglas Crockford.  In this case we pass the create function this so that it creates an instance of the current object.  The real “magic” of the extend function happens from lines 4 to 7.  What I’m doing here is looping through all the properties that were passed into the function and then adding them the new object.  The call to hasOwnProperty on line 5 ensures that   we only copy direct properties that were passed in and not properties added through the prototype chain.

The final piece of the puzzle is creating a parent property on the newObject and setting it to this.  By creating a parent property we can now call base object functionality in our new objects.  Here is a simple JSFiddle demonstrating the usage of extend.  First I created a simple basic base object.

   1:  var baseObject = {
   2:      name: function() {
   3:          console.log("Base");
   4:      },
   5:      extend: function(properties) {
   6:          var property, newObject;
   7:          newObject = Object.create(this);
   8:   
   9:          for (property in properties) {
  10:              if (properties.hasOwnProperty(property)) {
  11:                  newObject[property] = properties[property];
  12:              }
  13:          }
  14:          newObject.parent = this;
  15:          return newObject;
  16:      }
  17:  };

I then created a simple inherited object using extend:

   1:  var inheritedObject = baseObject.extend({
   2:      name: function() {
   3:          this.parent.name();
   4:          console.log("inherited");
   5:      }
   6:  });

Now when we create an inherited object and call name, we will get both base and inherited printed out:

   1:  var test2 = Object.create(inheritedObject);
   2:  //will print out "base" and "inherited"
   3:  test2.name();  

The extend function is something that gives us a lot of flexibility in creating objects.  Now that I’ve finally wrapped my head around it this will be something that I use a lot more in my projects moving forward.

Tags:

Exploring JavaScript Inheritance

by bhayden
23. June 2012 22:22

Earlier I posted about becoming polyglot programmer.  Since then I’ve done a lot of reading regarding JavaScript (finishing Crockford’s excellent book) and one thing I needed to wrap my head around was how to “properly” do JavaScript inheritance.  Being a classical based language developer, it’s easy to try and take what JS provides and make it into something that looks and feel familiar to me.  Of course doing that is kind of missing the point on truly learning JS.

In the meantime we began a major project at work where we were going to be rewriting our JavaScript.  This seemed like the perfect opportunity to finally wrap my head around inheritance.  To give some context we were using YUI 2 with some jQuery sprinkled in.  We made the decision to move to jQuery completely and to bring in Kendo UI. 

The first scenario that popped up was our address control.  We have a basic address control, containing the typical address fields (street, city, state, zip and country).  We then have a shipping address control which adds to the the address control a name and phone field.  The base object looks something like this:

   1:  Address = {
   2:      street: "",
   3:      city: "",
   4:      state: "",
   5:      zip: "",
   6:      country: "",
   7:      fill: function(data) {
   8:          this.street = data.street;
   9:          this.city = data.city;
  10:          this.state = data.state;
  11:          this.zip = data.zip;
  12:          this.country = data.country;
  13:      }
  14:  }

We added a fill method to pass data in from AJAX calls and populate the object. Ideally the shipping address object would look something like this:

   1:  ShippingAddress = {
   2:      name: "",
   3:      phone: "",
   4:      /* fields from Address */
   5:      fill: function(data) {
   6:          this.name = data.name;
   7:          this.phone = data.phone;
   8:          base.fill(data);
   9:      }
  10:  }

The question did cross my mind as to why these need to be separate objects at all, but I’ll leave that discussion for another time (and place).  The neat thing about JavaScript inheritance is that it is prototypical, and that means that we can tell our shipping address object that its prototype is the address control (the neat thing about this is that we’re basically telling the shipping address object that it has all the behavior of the address object).  This is easy enough:

   1:  ShippingAddress.prototype = Address;

While this work, it lacks elegance to me, and it seems like a lot of people agree on that one.  The other thing we would like to do is be able to easily add functionality to our base Address object because that’s what we’re really after here.  We need all the functionality of the Address plus whatever we want to add to it.  In order to do this we add an extend method to the Address object.  This method does three things: creates a new a object, copies any properties that we want to add and then sets a parent reference so that the inherited objects can reference its base functionality.  Our final address object looks like this:

   1:  Address = {
   2:      street: "",
   3:      city: "",
   4:      state: "",
   5:      zip: "",
   6:      country: "",
   7:      fill: function(data) {
   8:          this.street = data.street;
   9:          this.city = data.city;
  10:          this.state = data.state;
  11:          this.zip = data.zip;
  12:          this.country = data.country;
  13:      },
  14:      extend: function(properties) {
  15:          var property, object;
  16:          object = Object.create(this);
  17:          for (property in properties) {
  18:              if (properties.hasOwnProperty(property)) {
  19:                  object[property] = properties[property];
  20:              }
  21:          }
  22:          object.parent = this;
  23:          return object;
  24:      }
  25:  };

And the final shipping address object changes to this:

   1:  demo.ShipAddress = demo.Address.extend({
   2:      name: "",
   3:      phone: "",
   4:      fill: function(data) {
   5:          this.parent.fill.call(this,data.Address);
   6:          this.fillMe(data.Instructions);
   7:      },
   8:      fillMe: function(data) {
   9:          this.name = data.name;
  10:          this.phone = data.phone;
  11:      }
  12:  });

The fillMe function isn’t strictly necessary.  I used this.parent.fill.call and set the context so that I could make this a kendo observable object and the binding would work correctly.  If you execute it  normally then the binding doesn’t work.  This occurs because it appears that Kendo elevates the base object properties onto the shipping address object.

The Kendo piece of the puzzle is fairly simple.  I created a simple wrapper function to create a shipping address and then return that as an observable:

   1:  demo.shipAddressViewModel = function() {
   2:      var _address = Object.create(demo.ShipAddress);
   3:      return kendo.observable(_address);
   4:  };

To put the it all together into a usable block of code that does something:

   1:  var viewModel = demo.shipAddressViewModel();
   2:  viewModel.fill(dummyData);
   3:  kendo.bind($("#addressForm"), viewModel);

Here we create a view model and then bind it to an address form on our page.  I created a JSFiddle that puts this all together, including the HTML.

Tags: ,

5/30/2012 and 6/4/2012 Weigh-ins

by bhayden
4. June 2012 20:02

5/30 Weight - 203

6/4 Weight - 207

6/4 Sugars - 106

Weight shot up a bit the past week, which isn't good.  Time to strap Brandon on my back and start running around the block.  Sugars look to be doing good, which is a good sign.  My goal is to try and stay around 205 which might be a bit more difficult than I hoped but all it means is that I'll need to start seriously working out.

Tags:

5-21-2012 Weigh-in

by bhayden
21. May 2012 20:03

Weight - 203

Sugars - Unknown

I went to check my blood sugar this morning and it turns out that when the battery is low on my monitor it decides to no longer calculate.  The weight is going good, even though I had a complete and total diet meltdown on Saturday (pizza and cookies) but I can tell you one thing.  No matter how long you go without, there is nothing quite like biting into a soft, chewy chocolate chip cookie.  In the meantime, I'm involved in two major UI rewrites for two different companies.  By the end of these I think my goal of really understanding Javascript will be complete.

Tags:

Service Interruption

by bhayden
14. May 2012 19:45

It's been a few weeks since I last posted, which wasn't my intent but as I mentioned before I've been really busy.   Let's start with the first announcement, Amy's started a business and I've setup a very basic website: cloudcandies.com.  They had their opening weekend last weekend and did very well!

The last few weeks of weigh-ins have been up and down but I seem to be sticking around the 205 range.  Sugars spiked just a bit at 117 and now they are trending down.  Two more weeks and I'll be off Medifast officially, even though I'll still be eating a few Medifast meals a day to help keep the calorie count down.

Tags:

4-23-2012 Weigh-in

by bhayden
29. April 2012 22:03

Weight: 205

Sugars: 91

Up a few pounds this week, which isn't surprising really.  Lots of things going on that are making it hard to get back to working out but hopefully they will all pay off.  Sugars are still doing good with no medication which is awesome.

Tags:

RecentPosts