Friday, August 13, 2010

Passing arguments to an event handler in Javascript?

Okay, so you want to pass an argument to an event handler in your script? Should be easy, right? let's try...
function buttonClick(buttonNr)
{
    alert('You clicked button nr ' + buttonNr);
}

var button1 = document.createElement('div');
var nr= 1;
button1.onclick = buttonClick(nr);
Piece of cake. Now what's the fuss about, you may be asking. Well try running it...

"You clicked button nr 1"

But you didn't, did you? See the problem?

"But I specifically told it to run buttonClick with parameter 1 when I click the button"

Nope, you didn't. That's what you think you told it to do, but you actually told it to call the function buttonClick with parameter 1 right away (hence the popup), and assign  whatever that function returns to the onclick event. In this case it returns nothing, which means that when you try to click the button, nothing is exactly what happens.

Function name with parenthesis means run the function
Function name without parenthesis is a reference to the function

Take two...

Okay, so we need a function reference. Well, let's just make one on the fly like this then... No parenthesis. We should be good.
button1.onclick = function() { buttonClick(nr) };
Take that, javascript! I passed  a reference to a function that calls the function I want, with the parameter I want. Case closed! problem solved. Now let's call it a day and go home.

Not so fast, mate. Why don't you run a quick test first?

"Undefined???" But I defined it right there!


That may be true, but your event doesn't run right there. It's just assigned there. It's context when it actually runs is whatever element invoked it. In our case the button1 div. So your nr variable is not acessible.

"Well, let's just make the stupid variable global then and go home before dinner gets cold!"

That will work for a while. Until you introduce button 2.

You see you didn't pass the literal number 1 to the function. You passed a reference to the variable containing the number 1. Then you change it to contain the number 2 before you assign it to button 2, and suddenly it's 2 for button 1 as well.

Don't you hate the word reference by now?

Okay, before you start ripping your computer apart, I'll give you the magic formula. here you go. Do this, and nobody has to get hurt:
button1.onclick = (function (nr) {return function() {buttonClick(nr);} })(nr)
Huh?

Okay, let's break it down. A good programmer learns from his mistakes. What have we learned from our two previous mistakes?
  1. That when you put a parenthesis after a function it is called right away, and the result is assigned to the event handler.
  2. That the event handler function needs to run in a scope that has the parameter as a local variable.
Our solution is really a combination of those two lessons. Let's look at what we are in essence doing, by wasting some space. What if I put it like this?
contextWrapper = function(nr)
{
    var getEventHandler = function()
    {
        buttonClick(nr);
    }

    return getEventHandler;
}

button1.onclick = contextWrapper(nr);
So what we're doing is repeating our first mistake, but this time taking advantage of the fact that it calls the function and assigns it's return value to the event handler. And we're executing buttonClick in a context that retains its proper value for the nr variable.

So what is the value of button1.onclick after this? It's "function () { buttonClick(nr) }", where nr is fetched from the contextWrapper object surrounding it. So it retains its original value, no matter what you do.

Smart, eh? Now go make some crazy dynamic menus and tab bars and stuff and put it to use. Enjoy!

Saturday, May 29, 2010

A psalm for the psingle

Yes, I know how to spell single, but i felt like I needed another P there... Well anyways, a year ago, I was 25, single, lonely, without prospects of finding someone to share my life with. I had been obedient to the best of my knowledge and ability, and done things Gods way, but it didn't seem to bear any fruit. To the contrary, things seemed to go better for those who were disobedient.

Maybe you are in the same situation. You have prayed, done your very best, but time is passing and your friends are getting married and staring families one by one. The ungodly seem to be making progress, while the righteous are put to shame.

You are not the first one to think like that. I wasn't either. Probably even King David wasn't first, but he's the one who has articulated it best. Granted he's not writing in the context of having a hard time finding a wife, but the principle is still the same.Ungodliness might appear to yield the best return, but only short term. God will reward your faithfulness if you remain steadfast in him and do what is right. Hear David out:
Do not fret because of evildoers,
Be not envious toward wrongdoers.
For they will wither quickly like the grass
And fade like the green herb.
Trust in the LORD and do good;
Dwell in the land and cultivate faithfulness.
Delight yourself in the LORD;
And He will give you the desires of your heart.
Commit your way to the LORD,
Trust also in Him, and He will do it.
He will bring forth your righteousness as the light
And your judgment as the noonday.
Rest in the LORD and wait patiently for Him;
Do not fret because of him who prospers in his way,
Because of the man who carries out wicked schemes.
Cease from anger and forsake wrath;
Do not fret; it leads only to evildoing. 
Trust in the Lord, no matter what happens. He will not fail you. More than that: Rejoice in him! Understand that true joy is only found in him. Let your heart desire his way. When I experienced various temptations, I could not give in to them, because there was something I desired more. My goal was a marriage according to Gods will. And I knew no shortcuts would take me there. And that by trying such a shortcut I would in fact take my eyes off the goal and loose it.

God's will for you is good. When your heart desires Gods ways, your desire converges with what God desires most of all to give you. Commit your way to the Lord; obey his commands, down to the smallest detail. By doing that you walk the way that he has marked out for you. The way that leads to what your heart desires: His will.

Is all hope gone? It seemed like it for me this time last year. But we serve a sovereign God. And in a small church in Wisconsin there was a young woman thinking in similar terms. We knew each other a bit already, and knew we had many goals and desires in common. But because of the minor detail of the Atlantic ocean separating us, neither of us had thought anything would happen between us. But when I was going to a conference in Atlanta, her family invited me to visit them and drive down there together with them. we started talking more, and June 18. 2009 an email landed in her fathers inbox where I expressed my interest for her (I'll write more about that later). September 3. we got engaged, and on November 21. 2009, and the rest is, as they say, history. History that confirms that God is faithful.

Sunday, April 25, 2010

Never read a Bible verse!

Greg Koukl from Stand To Reason has a rule about Bible verses. It goes thusly:
Never read a Bible verse. That's right, never read a Bible verse. Instead, always read a paragraph at least. (str.org)
That's one of the best pieces of advice you can ever get when it comes to reading the Bible. Many don't realize that, while the concepts of chapters and verses are useful tools to reference scriptures, they are not part of the original inspired canon. In fact the Bible didn't even have verses until around the 15th or 16th century. (You can learn more about that on wikipedia).

So why can isolated bible verses be a bad thing? Consider what would happen if you tried to read any other form of communication in the same way as many read the Bible. Imagine if you for instance would divide this blog post into different units, each consisting of one or two sentences. And then in stead of reading it through from beginning to end would randomly select a sentence from it to read whenever you felt so inclined. Do you think you'd ever come to know what I was actually trying to communicate to you?

Yet that is how many read their Bibles. They'll pick verses here and there and view them as an isolated unit. Each verse is completely detached from its context and interpreted merely on its own. In stead of letting the text of scripture explain itself, they might pray about it or meditate on the verse, and then settle for some arbitrary interpretation that they feel God has shown them. They even regard this as the more spiritual approach to the Bible since they imagine it must involve close interaction with the Holy Spirit. Yet at they same time they might be unsettled about the amount of contradictions they seem to be finding in the Bible.

Consider, if you would, a jigsaw puzzle of roughly 32 000 pieces. Each piece represents a Bible verse. There are two ways to approach the individual piece. In both cases you would carefully look at the picture on each piece. You'll study it to see what it might be. An eye, a part of a flower, or what keeps every jigsaw puzzler up at night; a light blue piece that goes somewhere in the huge sky that makes up for half the puzzle.

So we've studied the piece. Now what? Well, one approach would be to select a handful of puzzle pieces that you think are particularly beautiful. The ones that "speak to you". And then put the rest of the puzzle back in the box before you lay out your pieces in different patterns until you "have a peace about it". And behold, there's your picture of God. It's a rather small one, and not quite rational. The pieces don't seem to fit very well together. But perhaps you see that as beautiful in itself. Like in a postmodern piece of art, the impossibilities and unintelligibility of it is a part of the artwork. And it allows you the luxury of interpreting it any way you want. After all, nobody can speak authoritatively of the meaning of a picture like that.

Then there's another approach. But few chose it, because it involves a lot of hard work, and the result isn't really open for interpretation. You don't get to put the plain or gray or dark colored pieces back in the box to devote your attention to the pretty and colorful ones. No piece can be left out. You don't merely study the pieces on their own, but you study other pieces that look like it, and find which ones go together, and which ones go in a different portion of the puzzle. There's no other way around it than to say it's a tedious task.

Yet shortly into the puzzle you start to see details emerging. Beautiful things, that you would never have gathered from staring at the individual pieces. You start to see that even the boring pieces when seen together forms a picture of beauty beyond what you could have ever imagined. And for each piece you put in you see a fuller picture of the glory of God. And have greater and greater assurance that once the last piece is in there that glory will be enough to keep you occupied for all eternity. This is how you should read the Bible. Not a piece here and a piece there, but paragraphs, chapters and books seen together. That's how you come to truly know what God is like.

Tuesday, March 30, 2010

Sunday trip with the wife

Spring is in the air, and my wife and I had a lot of fun stretching out legs a little on sunday. And we cracked ourselved up putting together a little vlog about it.



Make sure you visit our vlog-site to be the first to get the latest videos and updates.

Thursday, March 25, 2010

Does this picture offend you?

As a child, I remember watching, with great facination, a TV show about heart transplants. In spite of the degree of blood and gore, nobody felt that I needed to be shielded from that. I didn't feel particularly violated by it either. And I don't carry with me any lifelong scars from the experience.

This picture shows a kidney. If you browsed by this post with your child sitting on your lap, I doubt that you would feel any need to hastily cover their eyes while you browse away from it. If I put this picture on a sign, or on the side of a truck to protest kidney transplants, I doubt i would create much disgust among the general public. Although we usually prefer kidneys to be inside of our bodies, this picture simply isn't offensive enough to create any puplic outrage.

But what if it was a fetus?

Many try pass aborition off as just another surgical procedure where a piece of tissue is removed from a womans body. If that is true, than why would a picture of that piece of tissue offend you more than the picture if this piece of tissue?

Maybe because no matter how much we are able to decieve our minds there is something in out guts that says that piece of tissue is not much different than the piece of tissue I call my body. It's not a kindney, it's not an appendix, it's a murder victim.

Tuesday, March 23, 2010

How I met my wife

I promised in my post earlier today that my lovely wife and I would share a bit about how we got to know each other. And here it is. Our love story






If you want to keep up with our vlogs, follow us at for-ever-his.blogspot.com.

So what does she do for a living?

There were a number of questions I dreaded during my courtship with the wonderful young woman who is now my wife. One of them was "how did you meet?". With her being from the States and me from Norway, I guess that's an obvious question. But you can only explain that "we met through the internet, but it's not like that" so many times before you eventually just try to avoid the topic. On that note, we'll be posting a video on my wife's new blog where we share our story in the very near future.

Another question I dreaded was "what does she do for a living?". My answer, that she was staying at home working with her mom to learn the skills of homemaking, isn't exactly kosher in our feminist culture. And in most people's ears it largely synonymous with "nothing". Some, still looking for a good spin on the situation followed up by asking, "well, does she have an education?" When I explained that she didn't see education as a worthwhile pursuit for herself, their looks got even more puzzled. You see, in our culture women are valued in terms of careers and income. And in those terms, the wife I had chosen was worthless. Yet I knew that I had found a true treasure.

My wife has taken much heat for her stance against the subtle feminist attitudes that prevail throughout our culture. She has risen above the stigma of being a homemaker, and take great joy in adapting to her her new role as a wife, and hopefully soon a mother. If you ask her she will say that those are her highest calling. And I would add that it's the highest privilege for any husband and any child to be loved by a woman like that. It's worth so much more than the vacations, cars and other materialistic goods that we can't afford on a single income.

I've talked to several men who, though they're unwilling to depart with the extra income she provides, gets a certain look in their eyes at the thought of their wives staying home. Yes they discard it as completely unrealistic, but still they desire it. Several women too have disclosed to me that they wish they didn't have to work away from their husband and children. Yet materialism has them in it's grip.

My wife has started another blog, about being a homemaker. It's our hope that if you are carrying that desire this will help push you over the edge. You can find it at homemaker-by-choice.blogspot.com.

Related Posts Plugin for WordPress, Blogger...