Archive for the ‘JS/Flash’ Category

3Aug

When I first heard about ReactJS, CoffeeScript, Gulp and all these other new libraries I immediately thought “oh god why.” Over the past few months I’ve used each one separately, and learned about why they are cool or useful. Mostly the benefits involved less typing or some performance enhancement.

Slowly, I learned how to integrate all of these libraries and construct a usable workflow. Here’s my report on all of that.

Gulp/Browserify

Setting up gulp to use browserify is easy. You should; however, configure browserify to use the great `coffee-reactify` transformer. Make sure to first `npm install coffee-reactify –save-dev`

SublimeText

Install the “Better CoffeeScript” and “ReactJS” packages. They now support the “.cjsx” extension out of the box. I went ahead and configured all my .coffee files to use the that flavor of Coffeescript. To enable this click “View” -> “Syntax” -> “Open all with current extension as…” -> “ReactJS” -> “Coffeescript”. You may need to restart Sublime after this (I needed to).

Unit Testing with Mocha

First you should: `npm install coffee-react –save-dev`

Next you should set up your mocha.opts:

Finally, you’ll need to set up jsdom. You should start by running `npm install jsdom –save-dev`

Then set up a spec_helper like so:

This spec_helper attaches sinon to @ for every test it also exposes document and window as a global which ReactJS needs.

Now let’s write some tests:

In this test we stub out some Parse methods, create some fake elements using JSDom, Simulate a click and make sure some text is present. Everything a happy healthy test could ever want. Now with some great syntactic sugar.

Conclusions

The great thing about this workflow is that it is 100% browser independent. This makes your unit tests, well, more unit test like. You should of course create some sort of integration suite that tests your product in every browser.

If you need to integrate just one more library it is likely someone has already created something, just go explore! ūüôā To see some more code checkout a new project I’m working on:¬†https://github.com/parris/inventoryjs

Share
7Oct

Lately I’ve been working on a¬†client/server side validation library. I had a need to chain a bunch of methods together, and what that meant was a need to modify how the original functions were called without changing them. This lead to a need to pass some variables into a function and still wait to accept more parameters later. I already knew about currying, which I will¬†summarize as being able to pass as many variables as you feel into a function.¬†A couple other techniques were needed to solve this.

First I learned about the apply and call functions (I know I am late to the party…). In this case apply was extremely helpful, it let me set a context (change the value of this) and collect some parameters together and pass them into a function.

Next I discovered partial applications. This is more of a technique than anything else. In iz we have the following source code:

function validator_partial(fn) {
    //get all arguments except the first, which is the function name
    var args = Array.prototype.slice.call(arguments, 1);
    //pass the "value" in as the first parameter so that the user of this library doesn't need to
    args.unshift(value);
    //return a new function
    return function() {
        //combine all arguments made to this function with the ones above
        var allArguments = args.concat(Array.prototype.slice.call(arguments)),
        //get the result
        result = validators[fn].apply(null, allArguments);
        //update this object
        if (!result) {
            if (typeof this.error_messages[fn] !== "undefined") {
                this.errors.push(this.error_messages[fn]);
            } else {
                this.errors.push(fn);
            }
            this.errors.push(fn);
            this.valid = false;
        }
        //return "this" to allow for chaining of methods
        return this;
   };
}

for (var fn in validators) {
    //for each function, call the partial and pass in the function
    if (validators.hasOwnProperty(fn)) {
        Iz.prototype[fn] = validator_partial(fn);
    }
}

At the bottom I am grabbing the validators, and assigning them to the prototype of the Iz object. Before the validators get called though they go through a partial. This partial is a function that returns a function. The closure allows you to house some variables within it. When the returned function gets called it has access to the outer one’s scope, which is how you are able to pass in parameters before and after the function is called. On top of that this system lets you pass in as many params as you need and it simply forwards everything on.

With this method I was able to replace all of the first parameters (the ‘values’ with the value from the Iz object. This means less typing, which is always nice!

Share
6Aug
There are 2 problems with creating classes in JavaScript. 1) if you create classes in separate files you may need some system to tie the files up together for speed purposes. 2) typically your might lose your function names while you debug if you aren’t careful. In other words, you might be seeing tons of anonymous functions when you debug. There is a balancing act that goes on here.
How to define a class and methods typically:
Method 1:
function MyClass() {
}
MyClass.prototype.myfunc = function(){
}
Method 2:
function MyClass() {
   this.myfunc = function(){
   }
}
Method 3:
var MyClass = {
   myfunc : function() {
   }
}
In all 3 of these techniques you lose the name of the function in the debugger. Why? Well because your functions are technically anonymous.
function() {}
vs
function bob(){}
So how can we make this happen? Well… how about this:
MyClass.prototype.myfunc = function myfunc(){}
Yea, that actually won’t work everywhere unfortunately, but this will:
function MyClass{
   function MyClass_myFunc(){
   }
   this.myFunc = MyClass_myFunc;
}
It is a bit repetitive, but this will help you find where issues are occurring in a debugger. You debugger will now state the issue came from MyClass_myFunc() instead of (?). I believe some modern browsers do actually convert the (?) to the right function, but I believe it stops at some point in the call stack. So this is great!
Well you might also wonder how to namespace? What is a namespace in javascript anyways? Well a namespace like anything other than a “primitive” in javascript is an Object. It is defined:
var mynamespace = mynamespace || {};
This will either define a namespace named “mynamespace” as a new object literal OR it will use the existing mynamespace object in the current scope. So to add a class to our namespace we would just add our class to it:
function MyClass{
   function MyClass_myFunc(){}
   this.myFunc = MyClass_myFunc;
   mynamespace.MyClass = MyClass;
}
The problem with this is that we have both: MyClass the global defined and mynamespace.MyClass. To prevent this from occurring we wrap everything up like this:
var mynamespace = mynamespace || {};
(function() {
   function MyClass{
      function MyClass_myFunc(){
      }
      this.myFunc = MyClass_myFunc;</span></div>
      mynamespace.MyClass = MyClass;
}})();
Using the power of closures we have limited our globals to 1. We ONLY have mynamespace exposed globally. Nowwwww, we got 1 other thought that we should think about. What happens if our class depends on other classes? I’ve been looking at a good way to mimic Node.JS’s commonjs library client side. I think require.js will work well for this. How we might want to define our files with require.js:
var mynamespace = mynamespace || {};
require(["jquery"], function($) {
   function MyClass{
      function MyClass_myFunc(){
      }
      this.myFunc = MyClass_myFunc;
      mynamespace.MyClass = MyClass;
}});
Maybe? I think this looks good. It mimics the functionality we had earlier by limiting our global usage. You might be wondering what require is doing. Well, basically it is acting like a map. You specify where jquery is located and if it isn’t include it will get included. You can do this with all your classes in the app.build.js file defined by require. Note, that this does to some degree break from our notion of joining files together to optimize a website. While I am still investigating this, it seems that once a¬†dependency¬†is loaded requirejs will not load it again. This means that require might actually test for the¬†existence¬†of the dependency and if it isn’t around THEN load that file. This should allow you to use require’s optimizer to pull in various portions of a project at load then the rest later. Still reading, but this seems like the most optimal setup! ūüôā
By the way, using backbone.js also forces you to adhere to the above conventions!
Sources:
Share
16Sep

credits: http://www.tipb.com/2010/03/03/google-comments-apple-htc-patent-lawsuit/

First of, sorry for not posting a ton lately everyone. Been busy with letswoosh.com, rockin with Doomsday Machines, and making cool stuff at NetApp. In any case, if you are on this page, you have probably been searching endlessly for a way to get flash on your iP[ad|hone]. At work, we had a request straight from the VP of our department that ended up on my desk. “We would like to get about 200+ sales people to view training through mobile devices, namely the iPad,” was essentially the gist of the request. Well it just so happens that all of our training is done in Flash,¬† and around here they don’t seem to be big fans of going back to javascript. They asked me to come up with solutions.

There are essentially three ways I found that differ vastly from on another.

  • Jailbreak, then “un-jailbreak” once you install flash (I am not going to go into all of that)
  • Use smokescreen (source), a javascript version of the flash plugin, but it does not seem to work for interactive flash apps.
  • Provide a browser through a “VM”. That is host an app through some software server in the cloud.

Jailbreaking is out. We are not about to go to war with apple (although someone should). Smokescreen won’t really work out, plus it is not very “corporate ready,” which leaves us with the VM/cloud/SaaS solution. So via iPhone/iTouch I found an app called Cloud Browse. This is pretty nifty it is essentially Firefox hosted up in the cloud. It works, but there are some pitfalls. First of all, its unsupportable. If one of our clients says “ITS NOT WORKING” angrily all we can say is try again later? Also, it could potentially cost a ton, and its not a fixed cost. That is we need to buy subscriptions for each person who wants to use the app so they don’t end up on the generic/anonymous connection pool that may or may not get a connection depending on popularity at that moment in time. Do I need to mention that if you are going through some VPN service you are essentially exposing all your delicious corporate secrets? Lastly, it looks like crap on the iPad.

I mentioned the VM solution to my manager, and he said “OH, that kinda sounds like something Citrix probably does.” I did some research and found 2 must have apps and a pretty rockin video that explains a few things.

Step One (setup a server that doesn’t quite work yet for practice and experimentation):

Time to take down a fighter jet... Credits to: http://www.graphicsdb.com/img77239.htm

First thing you should do is follow the steps in the video below to get your Amazon cloud account all setup with XenApp 5.0. The AMI mentioned in the video doesn’t work with the iP[hone|ad]. I believe the AMI mentioned in the last link will work out though.

Next, log in and open up your “desktop” app, which may take up to 10 minutes even if it says “running” in amazon, server error means its still starting up. You will see all sorts of warnings about XenApp not having licenses, logins failing, terminal services needing licenses, but this is all normal and if you can open internet explorer you are doing just fine. At this point you may want to try adding apps into Citrix Access Manager, which is extremely easy (if you have a question about it feel free to ask in the comment section). I installed Firefox, Adobe Reader, Flash and AIR. I then installed an AIR application and was able to create apps in the manager tool. I used Firefox, the air application, and adobe reader.

Step Two (configure apps and reconfigure iP[ad|hone] and try it out):

You may want to add a new user. We will use this user to connect to the server via the iPad. The cool thing about having individual accounts is the same as doing so on a normal machine. Users can save their own settings and preferences. The same is applicable here.

Now go through App Store on the iPad. You can just download the Citrix Receiver for free. Go ahead and use your IP address as both the address and domain. You need have your username in the format: ComputerName\Username. If you are now able to open your web browser and launch it. Everything is working fine. Go to youtube.com and open up a video. There should be some choppiness as is expected, but hell it works. It may not be 24->30fps, but it gets the job done, and its supportable/secure.

Pricing:

At an enterprise level. This is extremely affordable. You only pay for XenApp once. The receiver is free. You may need to purchase Windows Server 2008 if you are doing this internally. Then for about 60 concurrent users we are looking at around 5 grand total. This is much more affordable than redeveloping a ton of software. One thing to note though. You should assess how much interest there actually is around all of this. The last thing you want to do is have a person dedicate about a week of their time trying to set this thing up and have no one ever use it.

Disclaimer:

Finally, let me put up a little disclaimer. I know nothing of these sorts of things. I just had a business need and tried my best to figure out how to get this to work. Questions shouldn’t necessarily be directed at me. Honestly I am not a subject matter expert for XenApp, Citrix, Windows Servers or iP[ad|hone]. Most of this stuff was pulled from best guesses and gleaned information. I will do my best to answer questions if I do receive them. In any case, I hope this was helpful to someone :)! Now I open the forum… Any other ideas?

https://www.citrix.com/English/ss/downloads/details.asp?downloadId=1864025&productId=186
Share
21Aug

gridzSo a few months ago I made this game on facebook with Edgar called Grid[z]. It is a simple little board game, but we have a ranking and score system that is based off ELO. ELO is the ranking system that is used for Top Coder and Chess Leagues among other things.

gridzWe have some planned modifications also including a public lobby that would allow players to invite each other. Also more stringent security policies are also needed. I don’t see this game becoming popular or making tons of money so I am considering it my first foray into the facebook api + cakephp. I may eventually post my cakephp library for making games; however, trying to validate player interactions with the server in a way to cover all cases seems to be a hurdle. It may be a nice starting point though.

Check it out: http://apps.facebook.com/gridzzz/

Share