Syntax problems in OO/Javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
DrPL
Forum Commoner
Posts: 26
Joined: Wed Oct 07, 2009 4:22 pm

Syntax problems in OO/Javascript

Post by DrPL »

Hi,
I'm teaching myself OO techniques to use on my webpages but the syntax on various on-line tutorials is a bit contradictory, for instance, when to use the "this" reference. I've hit a stumbling block on would like to ask for some help.
Basically, what I am trying to do is to instigate a few objects which, when loaded on a webpage will quickly load some
small images, and then display the images one after the other on random locations in a region on the screen. Then, the images will repeat again in another area. Ultimately, I'd like each object to have their own intervals before activating, so thats why I'm using Math.random() in one of the setInterval calls.

What I have so far is (removing lots of irrelevant junk)

Code: Select all

Display = function(idNo, n, fwImages, numImages)
{
	this.timerId = -1;
	imgArray = new Array();  // *
	this.loadCount=0;
	//this.loadImages(fwImages, numImages); //**
	loadImages(fwImages, numImages);
	var int1;
	this.xcoord=0;
	this.ycoord=0;
	this.myID = idNo;
	this.Frame =0;
	this.csselement = 'fwelement'+this.myID;
	this.start=start; //***

function loadImages(fwName, numImages)
{
	for(var i=0 ; i<numImages ; i++)
	{
		imgArray[i] = new Image();  //*
		this.imgArray[i].obj = this;
		this.loadCount++;
		this.imgArray[i].src = fwName+"/"+i+".gif"; // Load in the images
	}
}


function animate()
{
	if(this.loadCount < this.imgArray.length)
		return;

		if (Math.random()>.95)
		{
			this.xcoord = Math.floor(Math.random()*(450-117)); 
			this.ycoord = Math.floor(Math.random()*(250-99)); 
			this.intv1 = setInterval('activate()', 40);
		}	

}

function activate()
{


document.getElementById(csselement).style.top=xcoord;
document.getElementById(csselement).style.left=ycoord;

document[csselement].src = imgArray[tFrame];

Frame++;


if (Frame == imgArray.length )
{
window.clearInterval(intv1);
Frame=0; // after loop, return rocket frame to zero
}


}


function start()
{
	if(this.timerId == -1)
	{
		var f = animate();
		this.timerId = setInterval(f, (Math.random()+10)*10);
               // original use of this.timerId = setInterval('animate()', (Math.random()+10)*10); didn't work.
	}

}


}

The call to setInterval in start() is a problem. If I just put this.timerId = setInterval('animate()', (Math.random()+10)*10);
I get an error message saying that the function animate does not exist. After perusing some web sites, and using the
implementation above, I get an error saying 'useless setInterval call (missing quotes around argument?)'

The lines denoted by //* also present problems: when I try to run it, the console grumbles about my prefixing
imgArray with "this." The line with //** also had problems with the use of "this" and I had to remove this too.

My css and use of html elements is as follows:

Code: Select all

<style type="text/css">
.diorama { position:relative; height: 240px; width: 450px; background-image: url('backdrop.JPG'); }
.fw1{ position: absolute; z-index: 0; top: 155px; left: 301px;}
.fw2{ position: absolute; z-index: 0; top: 155px; left: 301px;}
.fw3{ position: absolute; z-index: 0; top: 155px; left: 301px;}
.fw4{ position: absolute; z-index: 0; top: 155px; left: 301px;}
</style>

<div class="diorama">
<img id=fw1" class=fw1 src="fw05/20.gif">
<img id="fw2" class=fw2 src="fw08/25.gif">
<img id="fw3" class=fw3 src="fw11/29.gif">
<img id="fw4" class=fw4 src="fw13/14.gif">
</div>
I'm trying to start off the whole thing with four objects as follows:

Code: Select all

function FWStart()
{

	myFW1 = new Display(1, 5, "fw05", 21);
	myFW2 = new Display(2, 5, "fw08", 26);
	myFW3 = new Display(3, 5, "fw11", 30);
	myFW4 = new Display(4, 5, "fw13", 15);

	myFW1.start();
	myFW2.start();
	myFW3.start();
	myFW4.start();
}


window.onload=FWStart;
But if I have the code without the line indicated by "//***", the console says that "myFW1.start is not a function". But, my syntax seems to be correct. Can some nice kind sould give me a few pointers (pun intended)?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Syntax problems in OO/Javascript

Post by VladSun »

Extracted from ExtJS:

Code: Select all

Object.prototype.apply = function(o, c, defaults)
{
    // no "this" reference for friendly out of scope calls
    if(defaults){
        Object.apply(o, defaults);
    }
    if(o && c && typeof c == 'object')
	{
        for(var p in c){
            o[p] = c[p];
        }
    }
    return o;
};

Function.prototype.createInterceptor = function(fcn, scope)
{
        var method = this;
        return !Ext.isFunction(fcn) ?
                this :
                function() {
                    var me = this,
                        args = arguments;
                    fcn.target = me;
                    fcn.method = method;
                    return (fcn.apply(scope || me || window, args) !== false) ?
                            method.apply(me || window, args) :
                            null;
                };
}

Function.prototype.createCallback = function(/*args...*/)
{
        // make args available, in function below
        var args = arguments,
            method = this;
        return function() {
            return method.apply(window, args);
        };
}


Function.prototype.createDelegate = function(obj, args, appendArgs)
{
        var method = this;
        return function() {
            var callArgs = args || arguments;
            if (appendArgs === true){
                callArgs = Array.prototype.slice.call(arguments, 0);
                callArgs = callArgs.concat(args);
            }else if (appendArgs != NaN ){
                callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
                var applyArgs = [appendArgs, 0].concat(args); // create method call params
                Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
            }
            return method.apply(obj || window, callArgs);
        };
}


Function.prototype.defer = function(millis, obj, args, appendArgs)
{
        var fn = this.createDelegate(obj, args, appendArgs);
        if(millis > 0){
            return setTimeout(fn, millis);
        }
        fn();
        return 0;
}

Code: Select all

function foo()
{
	this.value = 5;

	this.printValue = function()
	{
		alert(this.value);
	}

	this.delayed = function()
	{
		this.printValue.defer(1000, this);
	}
}

o = new foo();
o.delayed();
//or
o.printValue.defer(1000, o);
Take a look at http://dev.sencha.com/deploy/dev/docs/?class=Function for more cool features :)
There are 10 types of people in this world, those who understand binary and those who don't
DrPL
Forum Commoner
Posts: 26
Joined: Wed Oct 07, 2009 4:22 pm

Re: Syntax problems in OO/Javascript

Post by DrPL »

Argghh! I got your reply too late to implement it!
I've rejigged the code and got something working except that the animations I am trying to run through don't cycle on screen - I just get a broken icon symbol. I think its either something to do with the way images ae loaded in, or are displayed on screen using css. The sample code is at http://www.paullee.com/testpage4.html if anyone can take a look and help.
Post Reply