...

View Full Version : sprite.js advice



nikos101
11-21-2012, 02:25 PM
Hi, can someone explain what the first line does this sprite.js js file?


(function() {
function LoaderProxy() {
return {
draw: $.noop,
fill: $.noop,
frame: $.noop,
update: $.noop,
width: null,
height: null
};
}

function Sprite(image, sourceX, sourceY, width, height) {
sourceX = sourceX || 0;
sourceY = sourceY || 0;
width = width || image.width;
height = height || image.height;

return {
draw: function(canvas, x, y) {
canvas.drawImage(
image,
sourceX,
sourceY,
width,
height,
x,
y,
width,
height
);
},

fill: function(canvas, x, y, width, height, repeat) {
repeat = repeat || "repeat";
var pattern = canvas.createPattern(image, repeat);
canvas.fillColor(pattern);
canvas.fillRect(x, y, width, height);
},

width: width,
height: height
};
};

Sprite.load = function(url, loadedCallback) {
var img = new Image();
var proxy = LoaderProxy();

img.onload = function() {
var tile = Sprite(this);

$.extend(proxy, tile);

if(loadedCallback) {
loadedCallback(proxy);
}
};

img.src = url;

return proxy;
};

var spriteImagePath = "images/";

window.Sprite = function(name, callback) {
return Sprite.load(spriteImagePath + name + ".png", callback);
};
window.Sprite.EMPTY = LoaderProxy();
window.Sprite.load = Sprite.load;
}());

devnull69
11-21-2012, 02:34 PM
It's in fact the first and last line combined that create an immediately executing anonymous function.

This construct is often used to create a scope outside of the global scope.

nikos101
11-21-2012, 03:35 PM
It's in fact the first and last line combined that create an immediately executing anonymous function.

This construct is often used to create a scope outside of the global scope.

Hi, what is the point of that?

devnull69
11-21-2012, 03:47 PM
Sometimes you want to avoid "flooding" the global scope so that different scripts do not interfere with each other (for example by using the same names for separate variables that should be global to each script but that should not be used/overwritten by another one).

With the inner scope you create your own "namespace" for your variables and objects.

nikos101
11-21-2012, 04:19 PM
cool, wonder why does he write

$.noop instead of
function (){}

nikos101
11-21-2012, 04:26 PM
Any ideas how to convert this code into typescript?

nikos101
11-21-2012, 04:55 PM
Also this code is some of the most confusing I have ever seen, what is going on:

Sprite.load = function(url, loadedCallback) {
var img = new Image();
var proxy = LoaderProxy();

img.onload = function() {
var tile = Sprite(this);

$.extend(proxy, tile);

if(loadedCallback) {
loadedCallback(proxy);
}
};

img.src = url;

return proxy;
};

var spriteImagePath = "images/";


window.Sprite = function(name, callback) {
return Sprite.load(spriteImagePath + name + ".png", callback);
};



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum