Monday, September 3, 2012

Prototype is so handy

I have been javascripting like a madman recently. I now have quite a bit of experience in the language. Here's a few fiddles I did to get my head around stuff like objects, dragging stuff and AJAX calls:

My JsFiddles directory

Try the cards program, you can upload a picture and give it a name/description. It's supposed to be a jumping off point for making online card games like magic the gathering or w/e.

But what this has all served to do is increase my confidence in object oriented programming, and that really came out today.

Someone else's program

I have been fiddling with mobile accessibility on websites and instead of delving into the intricacies of mobile gestures and creating events to listen for, I decded to use a plugin. I decided on hammer.js.

The hammer.js system is to create a new "hammer" object out of the element you want to bind the tap events to. It's pretty handy and quite easy to use. you change this:

document.getElementById('element').addEventListener('touchstart', function(){});

To this:

var element = new Hammer(document.getElementById('element'));
element.ontap(function(){});

The problem I found with hammer.js is that when I created a new hammer object from an element, I could no longer access that elements attributes. My calendar script prints a table cell with custom attributes that I need to access in order to interact with the calendar. When looking for the attributes using (this).getAttribute('day'), I would get nothing, since (this) is not a DOM element, but a hammer object.

Enter prototype

The major advantage of javascript is that the source code is right there and you can change it to your hearts content (well, as long as it's not licensed etc). So I went right ahead and added my own function to assign my attributes to the object when I wanted to call events on my calendar.

Hammer.prototype.setCaldays = function(element){
  this.day = element.getAttribute('day');
  this.date = element.getAttribute('date');
  this.month = element.getAttribute('month');
  this.year = element.getAttribute('year');
  this.cumul = element.getAttribute('cumul');
 }

After writing all this I realize it might be completely confusing and useless to anyone but me reading, but fuck you I made things do stuff and I want to remember how. (I have revisited my UDK model import tutorial over a dozen times, so I think it's worth recording this stuff.)

No comments:

Post a Comment