Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

2011-01-20

(Desktop) Safari & (W3C) Geolocation API

I don't know why this thing fails in desktop Safari. I'm using Modernizr (which is bundled with the highly recommended HTML5 Boilerplate) which reports that the Geolocation API is supported but I'm unable to even get any dialog asking the user for permission to geolocate (which is, if I read the draft correctly, REQUIRED to be implemented).

Also, it seems that others (quite a few people actually) have had this same problem but I have been unable to find a solution yet. Below is a snippet from the code; in desktop Safari the PositionErrorCallback (the latter cb function) gets called after timeout but no luck with PositionCallback, no matter how long the timeout value is. Other tested browsers work as expected.

Referenced in other places:

(Note to self: check if Google Gears, which is still installed, is causing this?)

var position = null;

$(document).ready(function() {

    if(!Modernizr.geolocation) {
        return;
    }

    navigator.geolocation.watchPosition(
        function(pos) {
            position = {};
            position.lat = pos.coords.latitude;
            position.lng = pos.coords.longitude;
            position.allowed = true;
            init();
        },
        function(error) {
            position = {};
            position.allowed = false;
        },
        {
            enableHighAccuracy: false,
            timeout: 10000,
            maximumAge: 86400000
        }
    );

    checkposition();
});

function checkposition()
{
    log("checkposition()");
    if(!position) {
        setTimeout(function() {
            checkposition();
        }, 1000);
        return;
    } else {
        if(position.allowed) {
            log("checkposition(): got position: " + position.lat + "," + position.lng);
            fetchephemeris();
        } else {
            log("checkposition(): could not get a position, giving up");
            $("#geolocate").hide();
        }
    }    
}

2008-02-09

TODO: REST Describe & Compile Javascript code generation

The REST Describe & Compile generates code for PHP, Ruby, Python and Java. I'm working on a Javascript generator for REST Compile and decided to first write a working piece of code that I could use as a reference while implementing the actual code generator. This is the code so far (note: the term "class" used in comments is misleading because we're not really dealing with classes here):

// class auto-generated by REST Compile
function RestRequest() {
  // provide user and password for HTTP AUTH
  this.user = null;
  this.password = null;
  this.epoch = new Date(0);  // for If-Modified-Since brutality
}

// XXX: check this works with non-ascii characters etc.
RestRequest.prototype.urlencode = function(str) {
  return escape(str).replace('+', '%2B').replace('%20', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40');
}

// the GET function
RestRequest.prototype.doGetCall = function(uri, callback) {

  // XXX: seems to works on major browsers, check harder
  var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

  var async = (callback === undefined) ? false : true;

  // XXX: username, password not tested
  // XXX: isn't the user logged in already?
  if(this.user && this.password)
    request.open('GET', uri, async, this.user, this.password);
  else if(this.user)
    request.open('GET', uri, async, this.user);
  else
    request.open('GET', uri, async);

  // skip cache
  request.setRequestHeader('If-Modified-Since', this.epoch);

  if(async) {
    request.onreadystatechange = function() {
      window.status = request.readyState;
      if(request.readyState == 4) {
        callback((request.status == 200) ? request.responseText : null);
      }
      return;
    }
    request.send();
  }
  else {
    request.send();
    return (request.status == 200) ? request.responseText : null;
  }
}

// the POST function
RestRequest.prototype.doPostCall = function(uri, XXXDATA) {
    // XXX content-type
    // ...etc...
}

// class auto-generated by REST Compile
function Sleep(t) {
  this.params = {};

  // XXX: this should handle required params
  this.params['t'] = t;
}

Sleep.prototype = new RestRequest;

Sleep.prototype.prepareParams = function() {
  pStr = '';
  for(var i in this.params) {
    pStr += '&' + this.urlencode(i) + '=' + this.urlencode(this.params[i]);
  }

  // strip off the first '&'
  return pStr.length > 0 ? pStr.substring(1) : pStr;
}

// the optional Javascript callback function is given at this stage
// so that the constructor can be fed with just request parameters.
Sleep.prototype.submit = function(callback) {
  var requestUri = "sleep.php";

  if(undefined === callback)
    return this.doGetCall(requestUri + '?' + this.prepareParams());
  else
    this.doGetCall(requestUri + '?' + this.prepareParams(), callback);

  return;
}

The usage would be like (using jQuery to manipulate elements):

function synccall() {
  s = new Sleep(1);
  $('#sync').append('<p>' + s.submit() + '</p>');
}

function asynccall() {
  var s = new Sleep(2);
  s.submit(asynccallback);
}

function asynccallback(response) {
  $('#async').append('<p>' + response + '</p>');
}

Several questions came to mind while writing. Should there be some kind of error handling mechanism (definetely!)? An (optional) errback() function that would be fed with HTTP status and headers in case something went wrong, maybe? Because at this point the user would only get null back as a response and that is not too informative (and raising exceptions in a callback doesn't sound too clever either).

2007-10-22

Refer to the containing object in the jQuery callback function

From a Learning jQuery post by Mike Alsup:
...
var self = this;

$('#myElement').click(function() {
  // here you can use 'self' to reference
  // the enclosing object
});
...
Duh!

2007-10-16

qooxdoo Ajax framework

"qooxdoo is one of the most comprehensive and innovative Open Source multipurpose AJAX frameworks, dual-licensed under LGPL/EPL. It includes support for professional JavaScript development, a state-of-the-art GUI toolkit and high-level client-server communication."

May be worth checking out. Note: requires a basic Unix-ish build environment (shell, make, etc. + Python)..

2007-10-14

Bitmap-test

"Kind of" slow; maybe replacing the table with rows and columns of letters would speed it up. Next phase is to read (C header file -style) X PixMaps with XmlHttpRequest and display them add a 1-D Game of Life.

Bitmap.js:

function Bitmap( sizex, sizey, root, defaultcolor)
{
  this._sizeX =sizex;
  this._sizeY =sizey;
  
  this._scanline =[ ];
  this._tablename = root + 'BitmapTable';
  $( '#'  +root).append( '<table id=\"' +this._tablename +'\"></table>');
  for( var i =0; i <this._sizeY; i++)
  {
    this._scanline[ i] =[ ];
    $( '#' +this._tablename).append( '<tr id=\"' +this._tablename +'row' +i +'\"></tr>');
    for( var j =0; j <this._sizeX; j++)
    {
      this._scanline[ i][ j] =defaultcolor;
      $( '#' +this._tablename +'row' +i).append( '<td class=\"' +root +'BitmapTableCell\" id=\"' +this._tablename +'row' +i +'col' +j +'\"></td>').css( 'background-color', defaultcolor);
    }
    window.status =i + ' ' + j;
  }
}

Bitmap.prototype._sizeX;
Bitmap.prototype._sizeY;
Bitmap.prototype._scanline;
Bitmap.prototype._tablename;

Bitmap.prototype.getSizeX =function( )
{
  return this._sizex;
}
  
Bitmap.prototype.getSizeY =function( )
{
  return this._sizeY;
}

Bitmap.prototype.setPixel =function( x, y, color)
{
  this._scanline[ y][ x] =color;
}

Bitmap.prototype.getPixel =function( x, y)
{
  return this._scanline[ y][ x];
}

Bitmap.prototype.flip =function( )
{
  for( var i =0; i <this._sizeY; i++)
    {
      for( var j =0; j <this._sizeX; j++)
      {
        $( '#' +this._tablename +'row' +i +'col' +j).css( 'background-color', this._scanline[ i][ j]);
      }
    }
}

main.js:

function time( )
{
  return (new Date()).getTime();
}

$(document).ready( function() {
    var w =32;
    var h =32;

    var tinit =time( );
    var bitmap =new Bitmap( w, h, 'root', 'red');

    var tmanip =time( );
    for( var i =0; i <h; i++)
    {
      for( var j =0; j <w; j++)
      {
        bitmap.setPixel( j, i, ( i +j) %2 ? 'blue' :'green');
      }
    }

    var tflip =time( );
    bitmap.flip( );

    var tfinal =time( );
    var pixels =w *h;
    alert( 'create took ' + (tmanip -tinit) + ' ms (' + ( (tmanip -tinit) /pixels) + ' ms / pixel)\n'
    +'manip took ' + (tflip -tmanip) + ' ms (' + ( (tflip -tmanip) /pixels) + ' ms / pixel)\n'
    +'flip took ' + (tfinal -tflip) + ' ms (' + ( (tfinal -tflip) /pixels)   + ' ms / pixel)\n'
    +'total ' + (tfinal -tinit) + ' ms (' +  ( (tfinal -tinit) /pixels) + ' ms / pixel)\n');

    // load X pixmap image
    // ...
  });

main.css:

body {
    font-family : 'Lucida Grande', Arial, Helvetica, sans-serif;
    background : #000;
    color : #333;
    margin : 35px;
}

#rootBitmapTable {
    border : solid 4px #111;
    padding : 0px;
    border-spacing : 5px;
}

.rootBitmapTableCell {
    min-width : 10px;
    width : 10px;
    max-width : 10px;
    min-height : 10px;
    height : 10px;
    max-height : 10px;
    padding : 0px;
    margin : 0px;
    border : solid 1px #111;
}

2007-10-11

Glyphix jQuery Plugins

They provide jquery.xslTransform, "a jQuery wrapper for Sarissa, providing the ability to replace any element on the fly (using the browser's built-in XSLT engine) with the results from an XSLT transformation of an XML document." For example:

$('your-selector-here').getTransform('path-to-xsl.xsl','path-to-xml.xml');".

Sweet, looks as simple as it possibly could get. Requires jquery.debug and Sarissa.

2007-10-10

jQuery JavaScript library

"..a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages."

Some dude Simon Willison has a nice overview.

Another one from developerWorks.

2007-08-21

Javascript init( )

Always remember..

function init( )
{
    window.onload =function () { whateva( ); };
}

2007-03-23

JSLog

"..a lightweight, self-contained logging panel which takes the place of alert() boxes for your AJAX and DHTML applications."

2007-03-12

Javascipt: cross-browser event registration

var mozilla =document.getElementById && !document.all;
var ie =document.all;

function addevent( id, event, callback)
{
  if( ie)
      document.getElementById( id).attachEvent( 'on' +event, callback);
  else if( mozilla)
      document.getElementById( id).addEventListener( event, callback, true);
  else
    {
      // XXX???
    }
}