0

How to improve the following if-else structure in JavaScript?

if(isIE())
    if(termin != "")
        TargetElement.onclick = function() {merkzettelRemove(this, id, termin)};
    else
        TargetElement.onclick = function() {merkzettelRemove(this, id)};
    else
        if(termin != "")
            TargetElement.setAttribute("onclick","merkzettelRemove(this, " + id + ",
               '" + termin + "')");
        else
            TargetElement.setAttribute("onclick","merkzettelRemove(this, " + id + ")");
4
  • What do you want to improve? The only way I can think of too shorten this is using a Javscript Framework. Commented May 14, 2010 at 10:28
  • 3
    It would be improved if you used braces. Commented May 14, 2010 at 10:34
  • @Jens - there are plenty of ways to shorten this, none of which include adding a library. And improve doesn't necessary mean shorten. Commented May 14, 2010 at 11:08
  • @basit74, please accept the best answer if you are satisfied Commented May 14, 2010 at 11:32

7 Answers 7

5
// get a cross-browser function for adding events
var on = (function(){
    if (window.addEventListener) {
        return function(target, type, listener){
            target.addEventListener(type, listener, false);
        };
    }
    else {
        return function(object, sEvent, fpNotify){
            object.attachEvent("on" + sEvent, fpNotify);
        };
    }
}());

// add the event listener
on(TargetElement, "click", function(){
    // if termin is empty we pass undefined, this is the same as not passing it at all
    merkzettelRemove(this, id, (termin) ? termin : undefined);
});
Sign up to request clarification or add additional context in comments.

2 Comments

The problem is I think, on every click I have more and more event listeners. Is it true?
no :) you only add the listeners when calling on(... , and this is only done once right?
2

First things first, put some more braces in. It'll make it clearer what's going on, as well as saving untold heartache when you come to edit this in future.

Yes, you can get away without the braces if they wrap a single statement. When you come along three months from now and add something else into one of those blocks, your code will break unless you remember to wrap the whole block in braces. Get into the habit of doing it from the beginning.

2 Comments

I hadn't seen this when I left my comment on the question. This is the single biggest improvement to the code, I'd say.
It's not just to do with edits. In shows the intent better as well. Looking at the code above, it looks like the second if has two elses because of the poor indentation. Adding braces would make it obvious what goes where.
1

First, use { } everywhere, it will make your loops more readable.

Second: I think this does the same

if(isIE()) {
   TargetElement.onclick = function() {
            merkzettelRemove(this, id, termin || null); 
          };
 } else {
   TargetElement.setAttribute("onclick",
          "merkzettelRemove(this, " + id + ",'" + termin || null + "')");
}

Third, but you could try using unobtrusive javascript to add handlers to TargetElement

Comments

1

Firstly, lose the browser-sniffing. onclick= function... works everywhere; setAttribute is not only broken in IE, but also ugly. JavaScript-in-a-string is a big code smell; avoid. setAttribute on HTML attributes has IE problems and is less readable than simple DOM Level 1 HTML properties anyway; avoid.

Secondly, it would be ideal to make merkzettelRemove accept an out-of-band value (null, undefined, or even '' itself) as well as an omitted argument. It is possible it already allows undefined, depending on what mechanism it is using to support optional arguments. If so you could say simply:

TargetElement.onclick= function() {
    merkzettelRemove(this, id, termin || undefined);
};

If you must completely omit the argument and you don't want to use an if...else, there's another way around although IMO the clarity is worse:

TargetElement.onclick= function() {
    merkzettelRemove.apply(null, termin==''? [this, id] : [this, id, termin]);
};

Comments

0

I think using a Javascript framework is the best solution, but you can try something like this:

var src="merkzettelRemove(this, " + id + (termin && (",'" + termin + "'")) + ")";
if (isIE()) {
   TargetElement.onclick = new Function(src);
} else {
   TargetElement.setAttribute("onclick", src);
}

Comments

0

I know this is not an answer for your question, but if you don't have any reason for not doing so you should definitely use a library that cares about compatibility issues for you, such as jQuery. Then you could write something like this:

var el = $(TargetElement);

if (termin != "")
    el.click(function() {merkzettelRemove(this, id, termin)});
else
    el.click(function() {merkzettelRemove(this, id)});

3 Comments

I wouldn't necessarily say that jQuery 'cares' about compatibility issues :)
That the developers of jQuery aren't really known for their 'hi-quality' code - with frequent breakage between versions, especially with regards to supporting older browsers.
Uhm I didn't know about this. So far I hadn't any problem anyway.
0

how about using short circuiting operators. So the following code

if(A) {

if(B) { C; }
else{ D;} else{ if(E)
F; else G; } }

Will become

A && ((B&&C) || D || ((E&&F) || G));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.