I'm running into an error that I'm not sure how to resolve. I have the function update() below that takes in an object and then performs logic on it.
var requestAnimFrame = ( function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 10);
};
})();
function doAnimation(ballObject) {
requestAnimFrame(doAnimation);
update(ballObject);
console.log( getProperty("ball","top") );
console.log( getProperty("ball","left") );
}
function Ball(id) {
this.id = id;
this.xVel = .17;
this.yVel = .13;
this.ts;
}
function update(ball){
// do timestamp calculations
var newBall = ball;
var ts = Date.now();
newBall.ts = newBall.ts || ts;
var time_elapsed = ts - newBall.ts;
newBall.ts = ts;
// get values from ball
var ball_y = parseFloat( getProperty(newBall.id,"top").replace ("px", "") ) || 0;
var ball_x = parseFloat( getProperty(newBall.id,"left").replace("px", "") ) || 0;
// do other things, such as set new location for the ball's top and
// left position and etc.
}
// Code that starts the entire process
(function() {
ball = new Ball("ball");
doAnimation(ball);
})();
As you can see from this exert of my function above, I am trying to assign the property "ts" on the "newBall" object to the value held by the local variable named "ts". However, when I go to do that assignment, the entire value of the "newBall" object becomes the value of the local variable "ts" instead of just the "newBall" object's "ts" property. I'm assuming this is reflective of an error in my syntax, but I really don't have any clue? Does anyone have any ideas why this is happening?
I know that from c++ pointers, you have to de-reference the pointer before you can access the properties of the pointer object. Do I somehow have to do the same thing here?
EDIT: I have included my class declaration before my update() function, as well as the two functions that manage the repeated call to update.
The issue is on your doAnimation function:
function doAnimation(ballObject) {
requestAnimFrame(doAnimation);
update(ballObject);
/* Logging here */
}
When requestAnimationFrame calls your function again, it won't have the ballObject argument passed to it. In fact, it will be passed a high-resolution timestamp, which is what you're getting manually (with less precision) on the update function. For more information on how requestAnimationFrame works, check out the documentation at Mozilla Developer Network.
Going back to the ballObject argument, you need to use some other way to maintain reference to it. Normally in javascript this is achieved through closures:
function doAnimation(ballObject) {
requestAnimFrame(function() {
doAnimation(ballObject);
});
update(ballObject);
/* Logging here */
}
A working version of your example: http://jsbin.com/nebucedo/2/edit?js,output
Related
After reading this article regarding pure functions it seems to me that when working when object oriented JavaScript the concept of pure functions doesn't seem to be as simple to implement unless you want to end up calling functions with plenty of arguments or with an array of them.
Lets say I have the following function within a Javascript object.
function demo() {
var self = this;
//fixed in some other method
self.order.owner = null;
self.selectedEvent() = null;
self.order.booking_id = null;
self.order.order_id = null;
self.details = null;
self.notification = null;
self.notifyDesk = null;
self.additionalText = null;
//WILL THIS FUNCTION BE PURE?
self.test = function() {
if (self.order.owner && self.selectedEvent()) {
return true;
}
else if(self.order.booking_id == '4000' || !self.isValid(self.order.order_id) ){
return false;
}
return self.whatever;
};
return self;
}
var myDemo = new Demo();
//whatever other actions over the demo object here
console.log( myDemo.test() );
The method addOrder It is making use of 5 variables outside the function scope and belonging to the object scope.
That's not what I understood to be a "pure" function, but unless we want to call addOrder with 5 parameters, or a single array parameter with 5 elements, it doesn't seem to me we can get a pure Javascript function out of it.
This happens quite often in OO Javascript and accessing the object properties is something pretty common ?
What am I missing? Please delight me!
A pure function is one which for any input x will always produce the same output y and does not change any state. As long as the function does not break those principles, it's a pure function.
Here's an example showcasing the difference between a pure function and some impure functions:
var rect = {
width: 2,
height: 4
};
function areaPure(rectangle) {
return rectangle.width * rectangle.height;
}
function areaImpureMutate(rectangle) {
rectangle.area = rectangle.width * rectangle.height;
}
function areaImpureOuterState() {
// Uses variable declared outside of scope
return rect.width * rect.height;
}
console.log('pure:', areaPure(rect)); // no side effects
// Mutates state
areaImpureMutate(rect);
console.log('mutated:', rect.area);
// Relies on mutable state
rect.height = 5;
console.log('mutable state:', areaImpureOuterState(rect));
rect.width = 5;
console.log('mutable state:', areaImpureOuterState(rect));
The hard-and-fast rule for pure functions is that if I give you the same input regardless of the state of the rest of the program, it will always give me the same output and not mutate the state of the program directly.
So you could rewrite your test function like this to make it almost pure:
function test(obj) {
if (obj.order.owner && obj.selectedEvent()) {
return true;
}
else if(obj.order.booking_id == '4000' || !obj.isValid(obj.order.order_id) ){
return false;
}
return obj.whatever;
};
There's one problem with it: obj.selectedEvent() is an impure function which taints this pure function.
I would like to measure the computing time of methods.
A nice way is (How do you performance test JavaScript code?) with console.time('Function #1'); and console.timeEnd('Function #1');
My idea is to add these console outputs on lifecycle-methods. In this case using SAPUI5 like createContent:funtion(){}; methods.
This should be possible with AOP using before() and after() to runt the time counting.
Which AOP framework would you suggest and how to implement it with the need of modifying the identification string "Function #1" automatically?
There actually is no need for aspects in Javascript since you can change any function of any object at any time. JavaScript prototypes allows you to manipulate method implementations of all instances of an object at runtime. Here are two approaches for what you plan.
You could use a generic wrapper function:
var measureId = 0;
var fnMeasureFunction = function(fnToMeasure) {
console.time('measure'+ measureId);
fnToMeasure();
console.timeEnd('measure'+ measureId);
measureId++;
}
Admittedly that requires you to change your actual code...
For static functions or functions that belong to a prototype you could also do sth. like this from the outside without the need of any change to your existing code:
// any static function
var measureId = 0;
var fnOriginalFunction = sap.ui.core.mvc.JSViewRenderer.render;
sap.ui.core.mvc.JSViewRenderer.render = function() {
console.time('measure'+ measureId);
fnOriginalFunction.apply(this, arguments);
console.timeEnd('measure'+ measureId);
measureId++;
}
// any prototype function
var fnOriginalFunction = sap.m.Button.prototype.ontouchstart;
sap.m.Button.prototype.ontouchstart= function() {
console.time('measure'+ measureId);
fnOriginalFunction.apply(this, arguments);
console.timeEnd('measure'+ measureId);
measureId++;
}
This should be possible with AOP using before() and after() to runt the time counting.
As it already got mentioned, one really is not in need of real Aspect-oriented Programming
in order to solve such tasks in JavaScript. But this language might deserve some more standardized
method-modifiers in addition to the already existing bind method.
Please check back with my 2 most recent posts on this matter:
sandwich pattern in javascript code
Can you alter a Javascript function after declaring it?
... and how to implement it with the need of modifying the identification string "Function #1" automatically?
One does not need to since the console's time / timeEnd functionality only has to have
identical entry and exit points for measuring time (like the start/stop trigger of a stopwatch).
So one gets along with exactly the reference of the function/method one is currently running/measuring.
In order to solve the given task I will suggest around only instead of both before and
after for the former generates less overhead. The next code block exemplarily shows a
possible prototypal implementation. It also is the base for the afterwards following example
that finally might solve the OP's task.
(function (Function) {
var
isFunction = function (type) {
return (
(typeof type == "function")
&& (typeof type.call == "function")
&& (typeof type.apply == "function")
);
},
getSanitizedTarget = function (target) {
return ((target != null) && target) || null;
}
;
Function.prototype.around = function (handler, target) { // [around]
target = getSanitizedTarget(target);
var proceed = this;
return (isFunction(handler) && isFunction(proceed) && function () {
return handler.call(target, proceed, handler, arguments);
}) || proceed;
};
}(Function));
The next example takes into account that method-modification essentially relies on
functionality that is bound to an object. It is not just function wrapping. In order
to not loose the context a method is operating on, context has to be delegated /
passed around as target throughout all operations.
For this the example does not modify calculate since it is not bound to an object
but it modifies trigger instead.
var testObject = {
calculate: function (hugeInteger) {
var
i = hugeInteger,
k = 0
;
while (i--) {
k++;
}
return k;
},
trigger: function (hugeInteger) {
this.result = this.calculate(hugeInteger);
},
result: -1
};
console.log("testObject.result : ", testObject.result);
console.log("testObject.trigger(Math.pow(2, 26)) : ", testObject.trigger(Math.pow(2, 26))); // takes some time.
console.log("testObject.result : ", testObject.result);
console.log("testObject.someTrigger(0) : ", testObject.trigger(0)); // logs immediately after.
console.log("testObject.result : ", testObject.result);
testObject.trigger = testObject.trigger.around(function (proceed, interceptor, args) {
// before:
console.time(proceed);
// proceed:
proceed.apply(this, args);
// after:
console.timeEnd(proceed);
}, testObject); // omitting the 2nd argument - the [target] object - might break code that did work before.
console.log("testObject.trigger(Math.pow(2, 26)) : ", testObject.trigger(Math.pow(2, 26)));
console.log("testObject.result : ", testObject.result);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script>
(function (Function) {
var
isFunction = function (type) {
return (
(typeof type == "function")
&& (typeof type.call == "function")
&& (typeof type.apply == "function")
);
},
getSanitizedTarget = function (target) {
return ((target != null) && target) || null;
}
;
Function.prototype.around = function (handler, target) { // [around]
target = getSanitizedTarget(target);
var proceed = this;
return (isFunction(handler) && isFunction(proceed) && function () {
return handler.call(target, proceed, handler, arguments);
}) || proceed;
};
}(Function));
</script>
I'm reading DOM Scripting and have a beginner question about the abstraction below. The original code didn't include "clearTimeout", and "movement" was declared as a global variable. While the code ran fine, it wasn't a smooth animation which is why clearTimeout was added. My question however, is why I can't just test for "movement" and when it fails (on the first mouseover call to moveElement) continue on through the rest of the function? If I keep "movement" as a global variable, rather than make it a property, the code doesn't run at all?
If it helps to see the other JS and HTML, I've plugged the remaining code into jsFiddle.
function moveElement(elementID,final_x,final_y,interval) {
if (!document.getElementById) return false;
if (!document.getElementById(elementID)) return false;
var elem = document.getElementById(elementID);
if (elem.movement) { //Why can't I use "movement"?
clearTimeout(elem.movement);
}
var xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
if (xpos == final_x && ypos == final_y) {
return true;
}
if (xpos < final_x) {
xpos++;
}
if (xpos > final_x) {
xpos--;
}
if (ypos < final_y) {
ypos++;
}
if (ypos > final_y) {
ypos--;
}
elem.style.left = xpos + "px";
elem.style.top = ypos + "px";
var repeat = "moveElement('"+elementID+"',"+final_x+","+final_y+","+interval+")";
elem.movement = setTimeout(repeat,interval); //Originally global property
}
A property can never be undefined, only have a undefined as a value. In contrast, a variable may be undefined (not defined) or have undefined as a value.
When you say if (movement), in the case that movement is not defined, it will throw an exception.
When you say if (elem.movement), in teh case that elem.movement is not defined, it will evaluate to false and fail the condition without exceptions.
If you want to use movement as a global variable, you must first declare it before attempting to read from it via:
var movement;
function moveElement(elementID,final_x,final_y,interval) {
...
}
Alternatively, you could try to read the global movement as a property, since all global variables are just properties of the window object (in a browser):
if (window.movement) { // this will never throw an exception
clearTimeout(movement);
}
And finally, you could switch your if statement to one that protects itself against these exceptions via the typeof operator:
if (typeof movement !== 'undefined') {
clearTimeout(movement);
}
I'm just trying to structure my Javascript better and wondering how to incorporate window.onresize into the returned object, like so:
var baseline = function(){
var tall, newHeight, target, imgl, cur, images = [];
return {
init: function(selector, target){
this.images = document.querySelectorAll(selector);
this.target = target;
this.setbase(this.images);
window.onresize = this.setbase(this.images);
},
setbase: function(imgs){
this.imgl = imgs.length;
if(this.imgl !== 0){
while(this.imgl--){
this.cur = imgs[this.imgl];
this.cur.removeAttribute("style");
this.tall = this.cur.offsetHeight;
this.newHeight = Math.floor(this.tall / this.target) * this.target;
this.cur.style.maxHeight = this.newHeight + 'px';
}
} else {
return false;
}
}
}
}();
Is this the way that people would do it, is this going to work? Thanks
EDIT:
Invoked like so:
window.onload = function(){
baseline.init('img', '24');
};
I would like it so that when the window is resized, baseline.init is called with the same params as the initial init function call...
Here's the main error
init: function(selector, target){
this.images = document.querySelectorAll(selector);
this.target = target;
this.setbase(this.images);
// This line says call setbase now and assign the result of that
// as the onresize handler
window.onresize = this.setbase(this.images);
},
Your this.images does not point to the var images = [] you've created. This is for when you're using protoype style objects. You should just use images in your functions.
Some of your variables look like they're only used in setBase, they should be local
Looking at your object, it's very hard to tell what it's supposed to do, sounds like you're wrapping code in an object just for the sake of wrapping it into an object. What does baseline mean?
Here's a better version of your code, you should read and understand http://www.joezimjs.com/javascript/javascript-closures-and-the-module-pattern/ and http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html so you can decide what pattern you want to use and how they actually work. You are mixing both patterns, even though you didn't intend to. The trick is that with the way you're writing it (module pattern) there's no need to use this in the code, they're actually local variables held be the module
var baseline = function(){
// Don't use "this.tall", just "tall" gets you the variable
// Class variables, are you sure you need them throughout the class
var tall, newHeight, target, imgl, cur, images = [];
// Different name for the parameter so it doesn't get confused with
// the class variables
function init(selector, pTarget) {
images = document.querySelectorAll(selector);
target = pTarget;
setBase();
// Since we're not using this, you
// can just reference the function itself
window.onresize = setBase
}
// Most JS developers name methods using camelCase
function setBase() {
imgl = imgs.length;
if(imgl !== 0){
while(imgl--){
cur = imgs[imgl];
cur.removeAttribute("style");
tall = cur.offsetHeight;
newHeight = Math.floor(tall / target) * target;
cur.style.maxHeight = newHeight + 'px';
}
// should you return true here? what does returning
// something even mean here?
} else {
return false;
}
}
// Return just the public interface
return {
init: init
setBase: setBase
};
}();
I want watch for the creation of new global variables in Javascript so that, anytime a global variable is created, an event is fired.
I've heard of the watch() function but that is only for watching for specific variable names. I want a catchall.
If you already know which names pollute your global namespace (see Intercepting global variable definition in javascript), you can use this trick to figure out when does it actually happen:
window.__defineSetter__('someGlobalVar', function() {
debugger;
});
Be sure to have your developer tools open when you run this.
Obviously works only if your browser supports __defineSetter__ but that's true for modern browsers. Also, don't forget to remove your debug code after you've finished.
Found here.
I don't know how to make this work "on demand" as soon as a var is created, but I can suggest a polling approach. In a browser window, all global become a member of the global "window" object. (Because technically, "window" is the "global object"). So you could do something like the following:
1) enumerate all the properties on a window
window.proplist = window.proplist || {};
for (propname in window) {
if (propname !== "proplist") {
window.proplist[propname] = true;
}
}
2) Set a timer to periodically "poll" window for new properties
setInterval(onTimer, 1000);
3) Wake up on the timer callback and look for new props
function onTimer() {
if (!window.proplist) {
return;
}
for (propname in window) {
if (!(window.proplist[propname])) {
window.proplist[propname] = true;
onGlobalVarCreated(propname);
}
}
}
Afaik, .watch() is only SpiderMonkey (Firefox).
I played around with a polling function, I finally came up with this:
var mywatch = (function() {
var last = {
count: 0,
elems: {}
};
return function _REP(cb) {
var curr = {
count: 0,
elems: {}
},
diff = {};
for(var prop in window) {
if( window.hasOwnProperty(prop) ) {
curr.elems[prop] = window[prop]; curr.count++;
}
}
if( curr.count > last.count ) {
for(var comp in curr.elems) {
if( !(comp in last.elems) ) {
diff[comp] = curr.elems[comp];
}
}
last.count = curr.count;
last.elems = curr.elems;
if(typeof cb === 'function')
cb.apply(null, [diff]);
}
setTimeout(function() {
_REP(cb);
}, 400);
};
}());
And then use it like:
mywatch(function(diff) {
console.log('NEW GLOBAL(s): ', diff);
});
Be aware that this only handles new globals. But you can easily extend this for the case last.count > curr.count. That would indicate that global variables were deleted.
You cant have an event fired when some script does var v = 10, but as selbie said, you can poll the window object... I meant to suggest the same, but he beat me to it. Here's my other example... you count how many window objects are there, and execute GlobalVarCreated() function:
var number_of_globals = 0; //last known globals count
var interval = window.setInterval(function(){
var new_globals_count = 0; //we count again
for(var i in window) new_globals_count++; //actual counting
if(number_of_globals == 0) number_of_globals = new_globals_count; //first time we initialize old value
else{
var number_of_new_globals = new_globals_count - number_of_globals; //new - old
if(number_of_new_globals > 0){ //if the number is higher then 0 then we have some vars
number_of_globals = new_globals_count;
for(var i = 0; i<number_of_new_globals; i++) GlobalVarCreated(); //if we have 2 new vars we call handler 2 times...
}
}
},300); //each 300ms check is run
//Other functions
function GlobalVarCreated(){}
function StopInterval(){window.clearInterval(interval);}
You can load up that code in Chrome or FF console only change: function GlobalVarCreated(){console.log("NEW VAR CREATED");} and test it:
var a = 10
b = 10
String NEW VAR CREATED is displayed 2 times.