NDC 2014: SOLID CSS/JavaScript & Bower talks

This year I got invited back to Norway to speak at NDC Oslo 2014! It was one amazing event and if you ever get the chance to go, it truly is a one of a kind event.

Last year I got to speak about Glimpse, but this time round I got to share some of the lessons learnt out of developing the Glimpse client.

Amazingly, the organisers of NDC have already got the videos up and you can see my sessions down below:

Front End Design Patterns: SOLID CSS + JS for Backend Developers

As backend developers, we spent years perfecting and implementing the various patterns we use. These patterns allow us to exploit previous pain and experience, resulting in improved robustness of our code and increased efficiency of the coding process. At the same time we are finding it harder and harder to avoid working in the browser, and making unique and compelling end user experiences. With the experience we now have with client, similar benefits of using design patterns can be gained here.

Join Anthony van der Hoorn, as we look at what design patterns exist on the client and how we can use them. Once you know what patterns are at your disposal, you will start writing better code, that’s more maintainable and easier to read.

SolidTalk

Beyond NuGet: Front End Package Management with Bower

Package managers are becoming a way of life. For years now we have been using NuGet and have gained significant benefits within our applications and development process. That said, most of these benefits have trended towards server side improvements, rather than client side ones. Even though client focused packages do exist NuGet, they have never really been at home.

Join me as we look at what solutions have taken off in the front end development community for package management. We will be looking closely at Bower, NPM and more. We will see how these can be used within our existing .Net projects and what the differences are between NuGet and these other options.

BowerTalk

If you have any feedback or would like to ask any questions, feel free to reach out! Hope you enjoy.

OSS from the trenches – 7 Tips for Maintainers & Contributors

Open source software simply wouldn’t exist without the countless volunteers who give of their time to contribute to projects. These volunteers are the maintainers, contributors and advocates that make the OSS world go round. Countless reasons motivate people to get involved: the need to fix a bug that is preventing them from from using their project of choice, the desire to build their public profile, and even just an urge to “giving back”.

While it may appear that its up to these contributors to take the initiative to put themselves out there, it’s important to remember that its also up to the project creators and maintainers to help pave the way. Obviously, the amount of effort put into this “path building” needs to be proportional to the amount of help the maintainers are after and the size of the projects, but it rarely happens all on its own.

Given my own experience of running Glimpse, I’m clearly pretty interested in how OSS projects grow and stay healthy, so yesterday I turned to twitter to see what project owners and contributors alike had to say. I got a lot of great responses which, combined what I’ve learned through Glimpse, I’ll try and summarise here.

Heads up: this is a longer post than most. It’s broken down into Tips for Project Maintainers, and Tips for Project Contributors. I think you get a better perspective if you see things from both sides, but feel free to jump to the bit that you want to dig into.

7 Tips for Project Maintainers

There are a number of things projects maintainers can do to help encourage people to contribute, and to make it as simple as possible to get involved. As Jeff Handley of Nuget mentioned when asked, most of this seems to boils down to four simple steps:

  1. Easy on-ramp.
  2. Embrace.
  3. Recognize.
  4. Recognize…again.

A lot of the great thoughts and suggestions that got sent my way fell into one of these steps, but there are actually some very interesting (and more explicit) tips to bear in mind.

#1 Don’t be afraid to ask for help:

Its amazing how many people will lend a hand if you ask them for help in an area that they are knowledgeable about. This usually works best if you have a specific task or goal in mind, and an idea of when you would like it completed by. If approaching someone for the first time, also ensuring it’s a relatively small task that makes it easier for someone to say “Yes” when asked!

#2 Yell to the heavens when someone commits:

Unless you have specifically been asked not to do so, it’s usually advisable to use as many avenues as you have to thank people for their contributions (regardless of size) and publicly acknowledge them. Typically with Glimpse, we use our release notes to mention anyone who has contributed, and even go as far as mentioning those who submitted bug reports. We also try and thank our contributors by name when referring to features they have build or contributed to in talks, presentations and documentation.

Any time we have done this, our contributors have thanked us many times over and gone away with a massive warm fuzzy feeling – and this is exactly how we should be aiming to make our contributors feel. From here, they might go on to share what they have done with colleagues, or even gain the confidence to speak at user groups and contribute to other open source projects.

#3 Present front-and-center how people can contribute:

When someone has the desire to contribute, it’s important that they be able to understand how your community operates, what they can expect, and places where you could use some help. The best tool we could possibly offer is to make it clear what issues are currently the top of our priority list, marked using the “Jump In” tag that Nik Molnar brought to the table, presented with a few crucial requirements. As outlined in Nik’s post, these listed issues have the correct phrasing in that it doesn’t imply that something is necessarily simple or only for beginners. And about those crucial requirements:

  • Don’t swamp people by having too many issues in the list.
    • Its easy for people to get lost in the sheer volume of tasks that could be picked up, so having a concise list featuring a range of different tasks is a good place to start.
  • Keep the list up-to-date.
    • Nothing is worse than a list that is out of date or doesn’t represent your current needs. Ideally, the list you present people in the project site be synced with the issues that have that tag in GitHub.
  • Make sure these details can be easily found on your project site.
    • Ideally you would have a dedicated page on your site that is referenced everywhere that users can navigate to.

#4 Let people know what the expectations of your community are:

As a contributor, it would be fantastic to know what sort of turn-around I can expect when I submit a Pull Request for a feature or an issue. When you provide this information, if reassures the contributor that their Pull Request won’t be left for months on end without any feedback. Ideally you would even have a data point on your “contributor information” page which shows the average time to Pull Request acceptance or first response from the maintainers.

#5 Tell contributors the rules when it comes to contributing features VS fixing issues:

Within Glimpse, I love it when an unexpected Pull Requests come in. At the same time, I occasionally hold my breath waiting to see the size of the request and whether it’s to fix an issue or contribute a feature. Typically an issue fix is a slam dunk, as it only modifies a limited amount of code. On the other hand, a new feature could contain any number of changes and additional classes, and when that appears unexpectedly, it can be a lot to digest and fold into the code base.

In our case, it’s our responsibility to tell contributors that issues are fair game to start off as pull requests, but that we like to start off new features with an Issue so that we can talk about the approach, architecture, etc., lessening the surprises later on. You may prefer everything to start with the code and Pull Request in your project, but you should at least tell people about how you handle things.

#6 If someone commits an issue, ask if they are interested in making the fix:

In an ideal world, it would be amazing if people fixed their own issues and sent in pull requests, but in reality we naturally don’t expect everyone to do this. That said, given the chance, more people than you might expect would try contributing a fix if asked and provided a few helpful pointers…

#7 If using GitHub, setup your CI server to build Pull Request as they come in:

GitHub has the ability to notify interested parties when Pull Requests come in. If you setup your build server to listen to this (like we do on Glimpse with TeamCity), you can have the build server not only compile the code, but perform any pre/post build steps that may fail the build (i.e. stylecop rules, tests, etc). This lets the user know right away if they have a bad build (if they haven’t run the correct build steps before committing), and gives you confidence that the build, at a fundamental level, passes the initial test.

7 Tips for Project Contributors

In this wonderful world of Open Source, not all of the responsibility falls in the laps of the project maintainers. For projects to flourish, it requires volunteers to take the first leap of faith and open themselves to contributing. This is a scary prospect for a lot of people, as they are afraid of being criticized or publicly ridiculed. I’m ashamed to admit (as a member of the OSS community) that this does occasionally happen, but cases are becoming more rare and, when they do happen, the community is quick to act and rebalance itself. Bearing in mind that the community as a whole will appreciate your contributions, here are some good tips to help get you more involved:

#1 Doesn’t matter what you are doing, get it out there and make it open:

As developers, we usually have code snippets and libraries that we reference and come back to tucked away on our local machines. As a first step, feel free to create a GitHub repository and make these public.

In reality, it almost certainly doesn’t matter what your fears are regarding your IP, as it’s highly unlikely that someone would steal your code. And even if they do, it’s unlikely that a snippet or helper class you have is going to make them (and not you) a million dollars. What you are much more likely to get is someone thanking you for making their job a little easier if your code helps them out. And you will also have taken your first steps to making your code public – congrats!

#2 If you don’t want to put code out there, contribute to documentation:

Open source projects are renowned for not having the best documentation. You can help change this by updating documentation, sharing your experiences and knowledge (as you gain it) for everyone to benefit from. Most documentation for projects is now in a repository that you can access and submit updates to. If you’ve taken the time to improve someone’s documentation, then once again – congrats! (and thank you!)

#3 Go and find two or three bugs in a project you know:

This can be a great way to get started, as there are almost always bugs that need fixing. Set yourself a goal to fix these in your lunch hour, and give yourself two to three weeks to do so. Even if you only do this once, you will become a better developer for it, and learn new practices in the process.

#4 Its not about the code, its about the conversation:

If diving in with bug fixing leaves you with an urge to do more, it also will leave you with the need to discover the protocols that a given project has (i.e. how Pull Request are handled, etc), so it’s usually a good idea to chat to previous contributors. Tell someone “I want to do X, and here is how I’m going about it. Do you have any ideas of feedback?”. If you’re new to a project, you will probably get the best response if the feature is small to start with, and you can move onto bigger items as time goes on and your confidence grows.

#5 Contribute to more than one project:

Getting to the point that you feel comfortable enough to contribute just within one project usually take some time and effort. If you haven’t done this before, the thought of doing it for more than one project could be fairly daunting. However, bear in mind that the more code and the more people you interact with, the more practices and architecture you will observe, and this will only make you a better developer.

#6 Don’t be afraid, most projects are open to any help they can get:

I’ve listed a number of different ways you can get involved in projects. Yet for all that, I know that even with all this information, and with project maintainers making it as easy as possible for people to contribute, most potential-volunteers are still anxious about putting their code (and by a mis-apprehended proxy, themselves) in the public arena. To this I can only say: if this applies to you, start small and find something that you feel comfortable with. You will usually be amazed at how receptive the community is to your efforts.

#7 Submitting 1 fix to 1 Open Source project puts you in the top 1% of developers:

Most developers never even consider taking the time to contribute to an open source project. By taking that step and committing to a project, you are opening yourself to new experiences and opportunities. Grab this with both hands and take if for a spin – it’s the only way you’ll learn if you like it!

This isn’t an exhaustive list of suggestions, but hopefully it helps make your project easier for people to come to, or gives you the confidence you need to approach a new project and start committing. If you’ve got any questions or suggestions, let me know in the comments or on twitter!

Enjoying the Cold at WarmCroc!

Well, what a trip. I’ve just landed back in the country after an amazing conference at WarmCroc in Denmark – in the middle of their WINTER!

Need better shoes maybe?

Like you may have, when I saw where and when the conference was being held, and the fact that it was called “WarmCroc”, I had to look twice. At first I thought it was a prank, but after seeing the amazing lineup of speakers and the twitter traffic going I knew it was happening.

Mascot of Denmark?

For those who don’t know, WarmCroc is the brain child of one Daniel Frost. He had a vision of bring a world class conference to the doorstep of his fellow Danes. I am proud to say that he more than achieved this goal! The conference brought together one of the best lineup of speakers (outside of perhaps NDC/Øredev) I have seen in a long time, and I was proud to count myself amongst them. The sessions were really top notch, and even as a speaker, pretty much every slot had 2-3 (out of four) talks that I was keen to attend.

Working away with Daniel Frost and Scott Allen

The conference was kicked off by a Roy Osherove, who spoke eloquently about the art of leadership. From there, the fun continued and the sessions began. People were there from all over Europe, including Holland, Germany, Belgium, Denmark (or course) and even Italy. The entire conference had a fantastic vibe and was small enough that you got to know most people – around 225 devs where in attendance.

Sample of the Danish aggression I witnessed

My top pick for sessions were RavenDB & the magic beans by Ayende Rahien, xUnit.net and AutoFixture – better together! by Mark Seemann and Scaling Backbone Applications With Marionette by Derick Bailey. As for me, I ending up talking on Glimpse into ASP.NET and Building Agnostic Clients Through the Power of HTTP. I had a pretty great turn out, with really positive feedback all around, although I think I am going to try and “jazz” up the title of my talks, maybe “Kicking ASP.NETs ass with Glimpse” and “Kicking it to HTTP – Pragmatic REST”, partly an inside joke courtesy of Rob Ashton.

People at my talk
People at my talk

I ended up getting to know a lot of the locals and speakers alike – it was great to finally meet guys like Rob, Scott, Derick, Jimmy, Ayende, Mark, James, Roy, Henrik, and many more in person. The food was amongst the best I’ve had at a conference and where we ate was even decorated with taxidermy crocodiles and other animals for a bit more atmosphere. Again, I want to give a huge shout out to Daniel Frost, who really looked after us as speakers and made the conference what it was.

Viking lunch - OMG it was good.

I hope to go again in the future and advise you to never be scared off by conferences in middle of winter, in far off places, though you should definitely have better shoes than I did.

On the way there with Derick Bailey and Scott Allen

p.s. Danish danishes are amazing!!!! So much better an anything I’ve had anywhere else and I learnt that the Danes simply call them “Pastries” – who would have thought it, right?

Big screen Contre Jour and Paul Stack
Big screen Contre Jour and Paul Stack

jQuery Uri Templates

Uri Templates are one of those little known nuggets of goodness that not enough people know about. I was first introduced to them by Nik when we were creating the contracts between client and server for Glimpse.

jQuery Uri Templates

In this case the server was generating a Uri of a known type, but the structure of the Uri was to be determined by the server. So after some talking, we decided that a token system would work well, where the client would look for predetermined strings and replace them with the context data that the client – i.e. “/data?id={id}” would be replaced with “/data?id=123″, but if the server sent down “/data/{id}” the system would work just as well “/data/{123}”. Shortly after this discussion Nik came back and asked if I had heard about RFC6570. As it turns out, this specification does exactly what we wanted to do and a million times more. Cutting the rest of the story short, from v1 onwards, Glimpse now uses RFC6570 extensively.

Moving forward, out of that work and based on an offhand comment by Nik (who said that he wished jQuery would support RFC6570), I decided to set to work – a few hours later jQuery Uri Templates was born.

For detailed usage around how it works, best bet is to look on the site, but in short concepts like the following are supported:

Include script references: <script src=”jquery.min.js”></script>

<script src=”jquery-uritemplate.1.0.js”></script>

Example 1:
$.ajax({
    url: '/foo{?query,number}',
    tokens: {query:'person', number: '1234'}
});

Result:

/foo?query=person&number=1234

Example 2:
$.ajax({
    url: '/foo{?query,number}',
    tokens: { number: '1234'}
});

Result:

/foo?number=1234

Example 3:
$.ajax({
    url: '/map?{x,y}',
    tokens: {x: '123', y: '987'}
});

Result:

/map?123,987

Example 4:
$.ajax({
    url: '/map?{x,y}',
    tokens: {x: '123' }
});

Result:

/map?123

Example 5:
$.ajax({
    url: '/foo?fixed=yes{&x}',
    tokens: {x: '123' }
});

Result:

/foo?fixed=yes&x=123

Example 6:
$.ajax({
    url: '/foo{?list}',
    tokens: {list: [ "red", "green", "blue" ] }
});

Result:

/foo?list=red,green,blue

Example 7:
$.ajax({
    url: '/foo{?list*}',
    tokens: {list: [ "red", "green", "blue" ] }
});

Result:

/foo?list=red&list=green&list=blue

I really like this style of working with Uri’s and I think that it will become more important as RESTfull style semantics become more important – i.e. the consumer not knowing what Uri to navigate to next, etc.

Hope you find this useful.

Now working on Glimpse full time!

As some of you may have noticed, Nik (@nikmd23) and I have been working pretty hard on Glimpse lately. We have been able to put in loads of hours and have just about finished v1. As always, the community has been a huge help and we wouldn’t be where we are today without you.

For Nik and I, working on Glimpse has always been a passion and something that we have only just managed to fit into our spare time. Our vision and purpose has always been driven by trying to building great tools for developers, and make understanding your application easier. Many have “questioned” our sanity around making Glimpse free and Open Source – but we firmly believe in Open Source, are proud that we share our code and are trying to deliver what we believe should be in every ASP.NET developer’s tool box.

It turns out we are not the only ones who believe this. Recently we were contacted by Red Gate to see if we wanted to work on Glimpse full time. At first we weren’t 100% sure what this meant, and truth be told we were even a tad concerned about what this could mean given past events. However, after talking with the people at Red Gate, it is clear that they want to be able to give back to the community and support .NET Open Source.

After discussing in depth, it became exceptionally clear that they want to fully support Glimpse as much as they can. In practice this means that they will be paying Nik and I indefinitely to work on Glimpse full time! Talk about living the dream. On top of this, Nik and I still retain control over Glimpse. It also means that we will have the time and ability to speak about Glimpse and Open Source at various conferences and really see that Glimpse turns into what Nik and I had always hoped it would be. Lastly the licencing of Glimpse will stay the same and not change – unless the community decides that we need an even more liberal license than the Apache 2.0. This also means that we will be able to deliver more releases with more features and reliability more often.

Our collective vision for the future is that Glimpse will continue to evolve as a platform and that developers will be able to continue to use Glimpse in their day to day work. We want to see Glimpse evolve in a direction that gives the most we can to the community and becomes something that the community is proud to own. Longer term, we would like to see Glimpse run by the community itself (thinking jQuery style of ownership and management), and the circle of decision makers to grow beyond just us.

More specifically, in terms of upcoming releases and features, we believe firmly on shipping code and not just talking. But what I can say for sure is that v1 is very close to being ready and we have a list of ideas that we have waiting in the wings. We would love your feedback on our ideas and would love to add even more to the list. If you would like to pitch in to make more happen more quickly, feel free to ping us about getting a feature going and helping out.

I believe that this is an great time to be a part of the .NET Open Source community. Collaborations like this are happening more and more, and companies are starting to put serious meat and not just words behind our (the community’s) efforts.

If you have any questions, feel free to reach out – on twitter (@anthony_vdh) or on the mailing list. Also for the official Glimpse announcement, see out blog post here – http://blog.getglimpse.com/2012/09/06/were-on-it-full-time/

Make no assumptions: jQuery and JSONP

The implementation of JSONP in jQuery kinda sucks. Part of the point of jQuery is to abstract away the underlying differences between implementations (mainly browsers) and provide a common interface. You would think this is true across the board but its not quite – well at least when it comes to JSONP.

Support for JSONP is found within the Ajax part of the framework. When using this API, you make basic assumptions about the contact it presents – i.e. that is supports contrcuts like promises for all requests, or being able to have success/error/complete methods run if you provide them. It turns out that because of the abstraction that jQuery provides, this is true for all Ajax requests, except JSONP.

The guys who worked on this code obviously intended that people should be able to treat JSONP requests just like any other AJAX request – providing a nice level of abstraction and providing a common interface. But when it comes to JSONP, about the only contruct it does support is “success” – meaning if there is a 404 with your request or anything else goes wrong, “error” will never run, likewise, “complete” never runs as well. Due to the common API and the fact that these are fairly basic constructs which one could mistake quite easily should run for each type of request. It turns out this is the assumption that I made which had me scratching my head for quite some time.

In the defence of the authors, the documentation (http://api.jquery.com/jQuery.ajax/) does state that these constructs/handlers aren’t supported with JSONP, by my argument is that if so much isn’t supported, then it shouldn’t be a part of this interface. But I digress, I didn’t start this just to complain.

Given the fact that I don’t think its acceptable to not know whether your query/request has succeeded or not, I set out to find an alternative. In my search I found Julian Aubourg’s (@jaubourg) solution where he has provided the support for JSONP that should have been included out of the box (i.e. error checking)! – https://github.com/jaubourg/jquery-jsonp

See it, love it and use it. I don’t know why the guys in jquery have decided that JSONP should have better support out of the box, but at the current time there is no better alternative.

CSS – Custom bullet content in Unordered List

Today I had a case where I needed to have the semantics of a unordered list, but I wanted each bullet to have a different custom data value. Most of the time when something like this comes along, we want to change all the bullets from one symbol to another. But in this case I wanted some items to have their bullet replaced with “1″, others with “2″ and others with “3″.

Here is an example of what I wanted to do:
  1. This is really important
  2. This is important
  3. This is least important
  2. This is important
  1. This is really important

With this in mind I set off to find out how to do this and I came across various articles. A lot of these said that you had to revert to jQuery/JavaScript to do this and others showed how you could use a css property called “content” to show static content. This was great, but then I started to think that I actually wanted the value to be retrieved from an Attribute, hence allowing the data for the bullet to be dynamic. This this knowledge in hand I came across the following article http://css-tricks.com/css-content/ and put together the following code:

   
   ul.custom { list-style: none; }
  ul.custom > li:before { content: attr(data-content) '.'; }

  <ul class="custom">     <li data-content="1">Test</li>     <li data-content="3">Test</li>     <li data-content="2">Test</li>     <li data-content="1">Test</li>   </ul>

As it turns out this has the desired effect:
  1. Test
  3. Test
  2. Test
  1. Test

Hope that helps.

End of the road, the start of the unknown

It seems like that time of year when people look to the year ahead and decide if they want to find new work and take up new opportunities. For my part, I have spent almost the last two yeas on the rollercoaster ride which is New York City. All in all I have enjoyed my time and feel that it has been pretty successfully – having helped conceive and build Glimpse, delivering projects, speaking at conferences, travelling around the world and generally having a great time.

But the time has come and I’ve made the decision to move back to Australia. I am sad to leave but at the same time excited at the world of possibilities that await. I don’t currently have any work lined up, but by the time I’ve finished traveling and moved back, I’m sure I will find something that I can sink my teeth into. I’m not sure exactly what sort of work I will seek out, but one thing is for sure I love the web, love building interactive sites, working with passionate people and helping make users lives easier. I also know that I love the philosophies behind companies like 37signals, GitHub, etc. So if you know anyone who is looking for a passionate web developer, either show them Glimpse and/or let me know anthony.vanderhoorn{at}gmail.com.

Just incase anyone is worried, one thing I can say for sure is that Glimpse isn’t going anywhere and my passion for has only grown since starting it. In accepting a new job, I will ensure that I will have the ability to continue working on Glimpse and the community. We are currently getting very close to a finalized v1 and have plenty of new and exciting things planned. In addition, I want to continue blogging and speaking, and helping the community that has given so much and I love being a part of.

Javascript minification patterns: Structuring for maximum compression

When it comes to JavaScript compressing and minification, I’m sure that most of us out there take it for granted and really don’t think too much about how the minifier we are using actual works or what it can actually minify. It turns out the actual structure of our code can have a major impact on the amount of minificaiton can actually perform.

The golden rule of most minifiers is to start by compressing the name of any non public variables. The problem  is that most of us don’t realize exactly what is and what isn’t public when it comes to JavaScript. Fortunately, there are some common patterns and practices we can use to help minifiers do their job and get the most out of the process.

Structuring for maximum compression
Structuring for maximum compression

Lets have a look at the following very contrived samples:

Sample 1

var pubsub = {};

//Support
pubsub.supportMethod1 = function () { /*...*/; };
pubsub.supportMethod2 = function () { /*...*/; };
pubsub.supportMethod3 = function () { /*...*/; };

//Main
pubsub.publish = function (message, data) { /*...*/; };
pubsub.subscribe = function (message, func) { /*...*/; };
pubsub.unsubscribe = function (token) { /*...*/; };

the end result cannot be nearly as compressed as if we were to restructure our code into a more module design. The following shows how we might go able restructuring our code:

Sample 2

var pubsub = (function () {
    var //Support
        supportMethod1 = function () { /*...*/; },
        supportMethod2 = function () { /*...*/; },
        supportMethod3 = function () { /*...*/; },

        //Main
        publish = function (message, data) { /*...*/; },
        subscribe = function (message, func) { /*...*/; },
        unsubscribe = function (token) { /*...*/; };

    return {
        publish : publish,
        subscribe : subscribe,
        unsubscribe : unsubscribe
    };
}())

This altered code is very different to the first sample not only because it uses a module design patterns but this structure has the by product of protecting the variables.

This is a critical distinction as it means that minifiers can compress all variables except those that you are explicitly choosing to make public. This is possible with the first pattern but in my experience most developers writing JavaScript aren’t as conscious about this as they should be and in the end it results in code that is more bloated than it needs to be – even though its minified.

To show just what the difference can be look at the results when using Google’s Closure Compiler:

Sample 1

Original Size: 351 bytes (152 bytes gzipped)
Compiled Size: 166 bytes (91 bytes gzipped)
Saved 52.71% off the original size (40.13% off the gzipped size

var pubsub={supportMethod1:function(){},supportMethod2:function(){},supportMethod3:function(){},publish:function(){},subscribe:function(){},unsubscribe:function(){}};

Sample 2

Original Size: 405 bytes (180 bytes gzipped)
Compiled Size: 98 bytes (76 bytes gzipped)
Saved 75.80% off the original size (57.78% off the gzipped size)

pubsub=function(){return{publish:function(){},subscribe:function(){},unsubscribe:function(){}}}();

NOTE! The example I have provided is very trivial and one could argue that when these function have code, the saving in percentage terms wouldn’t be anywhere near as much. But in my experience since I started learning more about how JavaScript scoping works (what is public and hence what a minifier can’t compress) and making sure my scoping was correct, I started seeing:

  • More than decent reduction in file size as it turns out very few variables need to be public (in some cases none – meaning all variable names can be reduced)
  • I could understand my code better as I wasn’t choosing shorter names in an effort to help the minifier to its job
  • Lastly the quality of my code increased dramatically as it turns out the Module Pattern when implemented in JavaScript is fantastic way of of writing “good” JavaScript – which is one of the holy grails of web development

Best of luck!

UPDATE:

As @lordeagle pointed out, you can even take this further by assigning the values of statements that contain reserved words to variables. For instance, if you have a method that has multiple uses of “this”, at the start of the function you could assign this to a variable.

Gotchas: ASP.Net MVC 3 Release 1 – Razor – Import directives

Just a reminder that when using Razor (at least the version released with MVC 3 Release 1) isn’t the WebFroms view engine… I know this might be obvious but the things that you might overlook are things that we take for granted like the Import Directives in the web.config…

As far as I am aware these plus other options/settings are tied in with the standard ASP.Net view engine and aren’t known by Razor (at least at this point).

I learn’t this the hard way when trying to use Import Directives to save having to put using statements in my pages for the HTML Extensions that I’ve created… I was getting the following exception without knowing why (the lack VS support in Release 1 hurts a bit):

CS1061: ‘System.Web.Mvc.HtmlHelper<object>’ does not contain a definition for ‘ScriptCss’ and no extension method ‘ScriptCss’ accepting a first argument of type ‘System.Web.Mvc.HtmlHelper<object>’ could be found (are you missing a using directive or an assembly reference?)

It turns out that because Razor isn’t the standard view engine its not going to be looks for the Import Directives the same why the old view engine does.

Hope that helps.
Anthony