Moved to PatrickWalters.net

This blog has moved to PatrickWalters.net

Advertisements

Aurelia and JSPM – A match made in heaven

JSPM is awesome. To show how amazingly easy it is here is the worlds’ shortest tutorial –

Starter code

Grab the aurelia/skeleton-navigation repo.

git clone https://github.com/aurelia/skeleton-navigation.git

Install the dependencies listed there (npm install -g gulp, npm install -g jspm, npm install, then jspm install)

Now our base app is functional.

Add a new dependency from NPM

For this example let’s choose everyone’s favorite formatter – `markdown` – from npm –

jspm install npm:markdown

Use it

In the welcome.js view model add this import at the top –

import markdown from 'markdown'

And use the tool –

console.log(markdown.toHTML(''));

That’s it!

Few notes on JSPM install –

jspm install npm:markdown <~ tells jspm to install the package from npm named markdown. This allows us to import from markdown; without having to specify the exact path when using JSPM’s partner in crime, system.js.

SASS and SCSS in Visual Studio 2013 with Web Essentials – starring Compass and Susy

SCSS and Visual Studio 2013 with Web Essentials – Starring Compass and Susy

Intro

Since going to Build and seeing Mads Kristensen talk about the upcoming additions to Visual Studio 2013 with Update 2 and specifically what is new in Web Essentials I have been playing around with some of the new features.  A lot of these features are not yet well documented with how-to’s because they are so new so I wanted to blog about how easy it was to integrate SCSS into a VS2013 project.

In this post I am going to touch on using Compass and Susy to create our own styles in Visual Studio 2013.  I

Requirements

Resources

Lazy dev’s resources

The fun part

Let me start by saying that before starting this work I had no previous experience with Compass nor Susy, I do not have Ruby installed on my Windows machines, and I had almost no problems along the way with this set-up.  I received the SCSS and SASS Compass files from a designer and wanted to be able to take over their compilation and make sure that I could edit and maintain them as needed.  I would recommend having a build of Compass and Susy in SASS / SCSS file type already if possible, if not follow the instructions on their website to obtain it.  If you want to grab the built source check out the Github link for Compass and grab everything in that folder.

My first step was to bring all of the SCSS into my project.  The files that I brought in also contained SASS from a designer that needed to be converted but I will detail that more below.  I created a default ASP.NET MVC 5 project that the styles could be applied to for something like a style guide later.  Once I dragged and dropped all of the relevant files over we should be ready to rock.

Convert all SASS to SCSS

You may not need to do this, but if your project contains any SASS we need to convert it to SCSS file type.  The reason is that the SASS files do not appear to compile in Visual Studio without using any other plug-ins.  Also the SCSS syntax / format should be more familiar for most developers who are familiar with CSS and using brackets { } and semi-colons ;.  The SASS syntax follows the HAML indentation-style format which if you aren’t familiar with like me looks like Ruby.

I converted all of the SASS files very easily using the SASS to SCSS Converter website which is 100% free and extremely easy to use.  Simply copy the SASS into the left pane and proper SCSS is output on the right.  It can’t be any easier unless Web Essentials supported SASS to SCSS conversion, which it currently does not, but I am working on a plug-in for now to do it for you without leaving VS2013.

Fix all of the references

By default all the Compass files are happy with @importing their dependencies based on the namespace compass such as –

@import "compass/reset/utilities";

But we need to help Web Essentials find the dependencies using a more relative paths like this –

@import "../../reset/utilities";

The good thing is that once we start typing VS/WE will give us Intellisense to find the files without guessing.  The only thing that I noticed is that when you use Intellisense it wants us to use the fully-qualified file name (including the _ prefix and .scss format) which doesn’t follow SCSS convention.  It may work good either way but to follow convention remove the underscore and format.

NOTE : Along the way each individual SCSS Compass file will probably not compile properly.  The reason is that Compass uses Mixins and Variables that may not yet be available.  This is Ok!  We only need our main SCSS file to compile in the next step.

Let’s start using Compass!

After fixing all of the references and making sure we are only using SCSS file types we can create our own SCSS file to be the main style aggregate.  If you are incorporating Susy as well simply make sure to follow the same steps as we did with Compass above in fixing the references.  Create an application.scss in your project at the same or higher level as _compass.scss.  Simply right-click on a folder and ‘Add Item’ and search for SCSS file type.

Our project structure shouldn’t matter too much but this is what I am using for now –

  • application.scss
  • _compass.scss
  • _susy.scss
  • compass (dir)
  • susy (dir)

Using the @import directive will create a dependency on an other SCSS file, so let’s @import compass and susy

@import 'compass';
@import 'susy';

Now that Compass has provided us with a bunch of mixins and variables that we can use lets try it out.  For production we should separate our style logic into partials for good practice but for now let’s just do it right here in the application.scss  Add the following two lines to see our work in progress –

header {
  @include bleed;
}

Ok that doesn’t seem very beneficial.  What did we just do?  Susy has a mixin called bleed that can be applied and will give us some reusable margin and padding helpers to make our header bleed into columns.  Check out the mixin at susy/_padding.scss in your project to get a better understanding of what it is doing under the covers for us.

Compile it

By clicking save (or pressing Ctrl-S of course) we can save our SCSS and Voila! we should see the following output – 

header {
  margin-left: -1em;
  padding-left: 1em;
  margin-right: -1em;
  padding-right: 1em; }

This isn’t going to fix everything but it’s a good start.  Start creating some awesome stuff and feel free to link to it in the comments below

Changing the output directory and other settings

If you want to change where the CSS outputs to or change settings such as minifying the compiled CSS automatically you can do so by going to Tools/Options/Web Essentials/SASS and make your changes there.

Good luck!

Building the first SPA JavaScript game using Breeze.js and Durandal.js

So in the wild everyone is teaching you how to build a new enterprise application using single page application (SPA) architecture and libraries like Breeze.js.  I am a huge proponent of Breeze.js and what it can do for your application, but that is a different subject.  What I wanted to do now was share a project I am working on / building for a game contest that interests me.

Richard Garriott, the creator of Ultima Online, posted this challenge for developers to re-create a 1977 game called DND1 that was originally written in BASIC for a TeleType machine.  I started to try to figure it out and somewhere along the lines realized this would be fun to do in a single page application to show how powerful things like Breeze.js and Durandal.js can be for any purpose.

Check out the github here – http://github.com/PWKad/dnd-sota

Check out the working version of the game here – http://dnd.sotaexchange.com/

Let me know what you think in the comments!

jsBin for rapid prototyping

Until recently I was an avid user of jsFiddle.  I used jsFiddle to create and save the smallest examples of a problem or some front-end code I needed to test against.  I really think this helped me to write good re-usable code that I could always go back to and try to break or recreate an issue to see if it was that code or some other outside problem.

I started playing around with Ember.js lately and a lot of the examples and questions on StackOverflow.com reference the Ember jsBin.  I have been following @rem for a while on Twitter so I had seen the references to jsBin before but hadn’t really given it a shot.  When I started using it I realized some really neat things – 

1. Every time I needed a feature it was already there, and easy to find

2. It was embedded all over the web and working great (unlike a fiddle which was always just a link)

3. It was perfect for giving product teams a way to rapidly proto-type

At my current job we have a product team that likes to play around with styles.  They have gotten good enough with messing around with HTML to be able to mess around in Chrome to give us something to look at when building it out.  The problem is they have to screen shot it or copy – paste into an e-mail.

After playing with jsBin I decided to create a quick and dirty canvas for them to use for prototyping.  I figured it would take an hour or so to get it looking ok but there I was 10 minutes later with a non-functional but great looking snap shot of our web app.  I went to share it with our product team and realized there were a few options for sharing that were perfect for them to use – 

1. A live look at the output (that updates when changes are made to the bin)

2. An editable version for them to create screen mocks with

This was great.  This was exactly what product wanted to be able to share with customers and directly make changes to colors and such to allow them to give instant feedback.  They were able to immediately start prototyping new views and how they wanted them to look.

After sharing it the first time I immediately wanted to start a ‘fork’ of the project to try out a few extra things.  Boom, one of the first options I found was to ‘clone’ the bin.

Pro-tip to you – create your own jsBins and use them in your organization.  If nothing else it will get product off your back and give them something to play with.

Best parts about Durandal

I wanted to start a quick series dedicated to what makes Durandal so powerful to yield.

Part 1 – 

The Compose binding

With Durandal, you can dynamically load views and AMD modules directly from the DOM.  Why is this important?

  1. You can separate your views and modules into the smallest bits of (re-usable) code needed.
  2. Render your content more dynamically.
  3. You can easily instantiate and show either Singleton objects or Constructors.  (wait what?)

Separating your code

Imagine you want to create ‘n’ number of widgets that are in charge of their own visibility, data-fetching, and data-binding.  Easy.  Using the compose binding with a foreach, you can instantiate the modules in your view model and use the DOM to render them.

View –

<ul data-bind="foreach: widgets">
     <li data-bind="compose: widgetPath"></li>
</ul>

View Model –

define([], function () {
    var widgets = ko.observableArray();
    function initializeViewModel() {
        widgets.push(new Widget('Compose a widget module', 'viewmodels/exampleone'));
        widgets.push(new Widget('Compose a widget view only', 'exampletwo'));
    }
    function activate() {
        initializeViewModel();
    }
    function Widget(title, path) {
        var self = this;
        self.Title = title;
        self.widgetPath = path;
    }
});

What did we just do?

1. When we initiated the view model, we added two widgets into an observable array containing widgets.
2. The first widget is a path to a view model, which Durandal finds an associated view for and properly recognizes as part of a module.
3. The second widget is a path to a view, with no corresponding view model.

Whats interesting to note here is that in the first widget with a corresponding view model, Durandal helps us by creating a context around that view that is bound to the view model. This means if we reference something in the view model that Knockout and Durandal bind any related view elements to that instance of the view model. This is most ideal when not using singletons, as the every instance of a singleton will be bound to the same context.

In the second widget we are simply binding to the current context, which in this case would be the widget.  This is derived from the foreach binding that the widget is nested inside of, so you could easily bind to the title property or you could also reference the parent context using the Knockout $parent reference.

The reason $parent would not work in the first example is that the new context does not directly know who the parent is.  What if we wanted it to?  That’s easy as well, using activationData

Activation Data –

Using the activationData option of the compose binding, we can inject data or even context into the composed view model.  This is an excellent way of injecting dependency, and I could go on for hours on the various ways you can use this in your application, but let’s keep it simple and show an example.

Let’s bind our view up to widgets using Knockout’s containerless binding –

<!-- ko foreach: widgets -->
    <!-- ko compose: { model: widgetPath, activationData: { data: $data } } -->
    <!-- /ko -->
<!-- /ko -->

You’ll notice that I passing an object into the compose binding that contains a model and activationData, which contains an object of it’s own. You can read more on the Durandal website on the various parameters (http://durandaljs.com/documentation/Using-Composition.html) but basically the model is declaring that at that path, there is a view model to use for binding. Durandal automatically finds the corresponding view, and then injects our activationData into the view model. To intercept it, you only need to have a parameter in your activate method of the widget. Notice I am injecting $data, which basically just injects the current context into the view model. You could just as easily inject strings, observables, and even parent contexts.

Grabbing the data in our widget’s view model –

define([], function () {
    var thisContext = ko.observable();
    function activate(activationData) {
        // Set thisContext equal to the injected data
        thisContext(activationData.data);    
    }
    function Widget(title, path) {
        var self = this;
        self.Title = title;
        self.widgetPath = path;
    }
});

Now you can bind thisContext in the view however you want. A solid strategy is to use the with binding in your view that is set to thisContext, that way if for some reason your view model is instantiated without data it will just appear empty as opposed to breaking your bindings.

That’s it! Feel free to leave comments if you notice any problems or have any suggestions or questions. If you have any Durandal questions please direct them to StackOverflow.com or the Durandal.js Google Group, where the active community will help resolve them.

Knockout.js – why it’s not a framework

Many questions come up in reference to Knockout.js, and most of the time it is a developer who is new to the use of a JavaScript library such as Knockout.js who is coming from some other language and looking for what are the key tools to use.  Knockout provides developers with an easy to use two way data-binding paradigm that is rivaled by none (in my humble opinion)

Why is Knockout.js so hard to understand?  Meno’s idea of ‘The Learners Paradox’ references why this is so difficult in a new perfect way.  When Socrate’s asks Meno’s to find answers to something of which he does not yet understand, Meno’s replies that how could he seek out knowledge without the ability to know what to ask for.  

This perfect example illustrates why the Q&A style never works in computer programming.  The world of programming and computer technology is ever changing and as such it takes one more skilled than I to understand how to ask a question that has an answer for which you do not yet know of.  If you knew what the answer consisted of, and therefore knew the question to ask, why would you ask the question of others as opposed to the search engine of your choice?

The answer is that you wouldn’t.  As a self-respecting nerd, or anyone of any background, you would never ask a question of others unless you either knew the answer already and were seeking approval of your understanding of the answer, or you were too tired or lazy to look up the answer in the docs or whatever else was available at the time to you.

Knockout has the best doc’s of any JavaScript library available.  Period.  No other library or ‘framework’ keeps it as simple as Knockout.  Want to know the definitive answer?  Google it…  Boom, there it is.  Take Angular as an opposing example – When you google what you may be doing wrong in whatever portion of the code, you may get hundreds of results on how the author did it, as well as the Angular docs themselves which aren’t very definitive at all.  The Angular docs give examples of how it could be done, following the authors exact use case, and then go on into why each commenter disagrees with the OP or why the OP’s answer is wrong.  

Knockout’s area of concern is strictly related to two-way data-binding, and nothing else.  Want templating?  It’s there, but not great.  It’s there to provide the easiest way to perform the action that you intend to use without forcing you to use a specific methodology.  Want a data-library?  Then look no further than the plethora of libraries that provide such functionality.

Knockout.js is not an end-all framework or library that forces you to choose a path.  Knockout makes such an obvious choice for developers because it generally points you in the right direction.  Want to map simple objects from the server?  Use the mapping plugin.  Want to create form validation on the client?  Validation plugin…  Want to figure out how to create expert-level custom binding handlers?  Turn to StackOverflow.com, and users such as http://stackoverflow.com/users/594420/rp-niemeyer and http://stackoverflow.com/users/1287183/michael-best