Saturday 6 October 2012

JavaScript .getItemMetrics() : Metrics

Having recently crafted a nice little component for I wanted to share a little utility function that can be used as a basis to help create dynamic self-aware components. The concept is by no means new, I kind of borrowed it from Flex and this one uses jQuery so with a little jiggery pokery you can borrow it too. Here's the code...

com.middleweek.strip.prototype.getItemMetrics = function () {
 "use strict";
 var self = this;

 var item = {}; = self.createUUID();
 var renderedHTML = self._renderItem(self.renderers.stripItem, item);

 var metric = {};
 metric.width = $('#' +;
 metric.height = $('#' +;
 $('#' +;

 return metric;

Now, I quite like using this approach as it means I can style the component externally with CSS and not have to worry about injecting these values into the component or worse, hard-coding these values inside the component as I started off doing.

If you want to return a typed Object, perhaps called Metrics as the blog title suggests, you can either create yourself a predefined JS 'Class' and return that or have a Closure function inside getItemMetrics() and create and return an instance of that...

 function Metrics(w,h) {
 "use strict";
  this.width = w;
  this.height = h;
 var jqCache = $('#' +;
 var metric = new Metrics( jqCache.outerWidth(), jqCache.outerHeight() );

 return metric;


No comments:

Post a Comment

The internet is a crazy place so please help us keep it under control by leaving only relevant messages and comments, thanks a bunch! :m)