Search Results

Search found 6 results on 1 pages for 'phubarbaz'.

Page 1/1 | 1 

  • Javascript Inheritance Part 2

    - by PhubarBaz
    A while back I wrote about Javascript inheritance, trying to figure out the best and easiest way to do it (http://geekswithblogs.net/PhubarBaz/archive/2010/07/08/javascript-inheritance.aspx). That was 2 years ago and I've learned a lot since then. But only recently have I decided to just leave classical inheritance behind and embrace prototypal inheritance. For most of us, we were trained in classical inheritance, using class hierarchies in a typed language. Unfortunately Javascript doesn't follow that model. It is both classless and typeless, which is hard to fathom for someone who's been using classes the last 20 years. For the last two or three years since I've got into Javascript I've been trying to find the best way to force it into the class model without much success. It's clunky and verbose and hard to understand. I think my biggest problem was that it felt so wrong to add or change object members at run time. Every time I did it I felt like I needed a shower. That's the 20 years of classical inheritance in me. Finally I decided to embrace change and do something different. I decided to use the factory pattern to build objects instead of trying to use inheritance. Javascript was made for the factory pattern because of the way you can construct objects at runtime. In the factory pattern you have a factory function that you call and tell it to give you a certain type of object back. The factory function takes care of constructing the object to your specification. Here's an example. Say we want to have some shape objects and they have common attributes like id and area that we want to depend on in other parts of your application. So first thing to do is create a factory object and give it a factory method to create an abstract shape object. The factory method builds the object then returns it. var shapeFactory = { getShape: function(id){ var shape = { id: id, area: function() { throw "Not implemented"; } }; return shape; }}; Now we can add another factory method to get a rectangle. It calls the getShape() method first and then adds an implementation to it. getRectangle: function(id, width, height){ var rect = this.getShape(id); rect.width = width; rect.height = height; rect.area = function() { return this.width * this.height; }; return rect;} That's pretty simple right? No worrying about hooking up prototypes and calling base constructors or any of that crap I used to do. Now let's create a factory method to get a cuboid (rectangular cube). The cuboid object will extend the rectangle object. To get the area we will call into the base object's area method and then multiply that by the depth. getCuboid: function(id, width, height, depth){ var cuboid = this.getRectangle(id, width, height); cuboid.depth = depth; var baseArea = cuboid.area; cuboid.area = function() { var a = baseArea.call(this); return a * this.depth; } return cuboid;} See how we called the area method in the base object? First we save it off in a variable then we implement our own area method and use call() to call the base function. For me this is a lot cleaner and easier than trying to emulate class hierarchies in Javascript.

    Read the article

  • Getting Query Parameters in Javascript

    - by PhubarBaz
    I find myself needing to get query parameters that are passed into a web app on the URL quite often. At first I wrote a function that creates an associative array (aka object) with all of the parameters as keys and returns it. But then I was looking at the revealing module pattern, a nice javascript design pattern designed to hide private functions, and came up with a way to do this without even calling a function. What I came up with was this nice little object that automatically initializes itself into the same associative array that the function call did previously. // Creates associative array (object) of query params var QueryParameters = (function() {     var result = {};     if (window.location.search)     {         // split up the query string and store in an associative array         var params = window.location.search.slice(1).split("&");         for (var i = 0; i < params.length; i++)         {             var tmp = params[i].split("=");             result[tmp[0]] = unescape(tmp[1]);         }     }     return result; }()); Now all you have to do to get the query parameters is just reference them from the QueryParameters object. There is no need to create a new object or call any function to initialize it. var debug = (QueryParameters.debug === "true"); or if (QueryParameters["debug"]) doSomeDebugging(); or loop through all of the parameters. for (var param in QueryParameters) var value = QueryParameters[param]; Hope you find this object useful.

    Read the article

  • Get Func-y v2.0

    - by PhubarBaz
    In my last post I talked about using funcs in C# to do async calls in WinForms to free up the main thread for the UI. In that post I demonstrated calling a method and then waiting until the value came back. Today I want to talk about calling a method and then continuing on and handling the results of the async call in a callback.The difference is that in the previous example although the UI would not lock up the user couldn't really do anything while the other thread was working because it was waiting for it to finish. This time I want to allow the user to continue to do other stuff while waiting for the thread to finish.Like before I have a service call I want to make that takes a long time to finish defined in a method called MyServiceCall. We need to define a callback method takes an IAsyncResult parameter.public ServiceCallResult MyServiceCall(int param1)...public int MyCallbackMethod(IAsyncResult ar)...We start the same way by defining a delegate to the service call method using a Func. We need to pass an AsyncCallback object into the BeginInvoke method. This will tell it to call our callback method when MyServiceCall finishes. The second parameter to BeginInvoke is the Func delegate. This will give us access to it in our callback.Func<int, ServiceCallResult> f = MyServiceCall;AsyncCallback callback =   new AsyncCallback(MyCallbackMethod);IAsyncResult async = f.BeginInvoke(23, callback, f); Now let's expand the callback method. The IAsyncResult parameter contains the Func delegate in its AsyncState property. We call EndInvoke on that Func to get the return value.public int MyCallbackMethod(IAsyncResult ar){    Func<int, ServiceCallResult> delegate =        (Func<int, ServiceCallResult>)ar.AsyncState;    ServiceCallResult result = delegate.EndInvoke(ar);}There you have it. Now you don't have to make the user wait for something that isn't critical to the loading of the page.

    Read the article

  • Finite Numbers and ExplorerCanvas

    - by PhubarBaz
    I was working on my online mathematical graphing application, CloudGraph, and trying to make it work in IE. The app uses the HTML5 canvas element to draw graphs. Since IE doesn't support canvas yet I use ExplorerCanvas to provide that support for IE. However, it seems that when using excanvas, if you try to moveTo or drawTo a point that is not finite it loses it's mind and stops drawing anything else after that. I had no such problems in Firefox or Chrome so it took me awhile to figure out what was going on. Next I discovered that I needed a way to check if a variable was NaN or Inifinity or any other non-finite value so I could avoid calling moveTo() in that case. I started writing a long if statement, then I thought there has to be a better way. Sure enough there was. There just happens to be an isFinite() function built into Javascript just for this purpose. Who knew! It works great. Another difference I discovered with excanvas is that you must specify a starting point using a moveTo() when beginning a drawing path. Again, Chrome and Firefox are a lot more forgiving in this area so it took me a while to figure out why my lines weren't drawing. But, all is happy now and I'm a little wiser to the ways of the canvas.

    Read the article

  • ExplorerCanvas and JQuery

    - by PhubarBaz
    I am working on a Javascript app (CloudGraph) that uses HTML5 canvas and JQuery. I'm using ExplorerCanvas to support canvas in IE. I recently came across an interesting problem. What I was trying to do is restore the user's settings when the page is loaded. I read some information from a cookie that I set the last time the user accessed the application. One of these settings is the size of the canvas. I decided that the best place to do this would be when the document is ready using JQuery $(document).ready(). This worked fine in browsers that natively support the canvas element. But in IE it kept getting errors the first time I would hit the page. It seemed that the excanvas element wasn't initialized yet because I was getting null reference and unknown properties errors. If I refreshed the page the errors went away but the resized canvas wasn't drawing on the entire area of the canvas. It was like the clipping rectangle was still set to the default canvas size. I found that the canvas element when using excanvas has a div child element which is where the actual drawing takes place. When I changed the width and height of the canvas element in document.ready it didn't change the width and height of the child div. Initially my solution was to also change the div element when changing the canvas element and that worked. But then I realized that having to refresh the page every time I started the app in IE really sucked. That wouldn't be acceptable for users. Since it seemed like the canvas wasn't getting initialized before I was trying to use it I decided to try to initialize my app at a different time. I figured the next best place was in the onload event. Sure enough, moving my initialization to onload fixed all of the problems. So, it looks like the canvas shouldn't be manipulated until the onload event when using ExplorerCanvas. There might be ways to do it when the document is ready. I found some posts on initializing excanvas manually, but for me waiting until onload worked just fine.

    Read the article

  • Get Func-y

    - by PhubarBaz
    I was working on a Windows form app and needed a way to call out to a service without blocking the UI. There are a lot of ways to do this but I came up with one that I thought was pretty simple. It utilizes the System.Func<> generic class, which is basically a way to create delegates using generics. It's a lot more compact and simpler than creating delegates for each method you want to call asynchronously. I wanted to get it down to one line of code, but it was a lot simpler to use three lines.In this case I have a MyServiceCall method that takes an integer parameter and returns a ServiceCallResult object.public ServiceCallResult MyServiceCall(int param1)...You start by getting a Func<> object for the method you want to call, in this case MyServiceCall. Then you call BeginInvoke() on the Func passing in the parameter. The two nulls are parameters BeginInvoke expects but can be ignored here. BeginInvoke returns an IAsyncResult object that acts like a handle to the method call. Finally to get the value you call EndInvoke on the Func passing in the IAsyncResult object you got back from BeginInvoke.Func<int, ServiceCallResult> f = MyServiceCall;IAsyncResult async = f.BeginInvoke(23, null, null);ServiceCallResult result = f.EndInvoke(async);Doing it this way fires off a new thread that calls the MyServiceCall() method. This leaves the main application thread free to update the UI while the method call is running so it doesn't become unresponsive.

    Read the article

1