matt
matt

Reputation: 44303

javascript jquery: Overwriting variables - how? better performance?

Hey guys, i'm not much of a hardcore coder and so I don't get this basics here.

Imagine I have multiple 's on my page (that contain Youtube Videos via swfobject). All those object's have a unique ID like ytplayer_12, ytplayer_2, ytplayer_56, etc.

I need to run through all of this ytplayer_'s with jquery and add an EventListener to them.

It works just fine! I just wonder if I'm declaring the variables ($ytid, ytid) in the right place - outside of the onYouTubePlayerReady() function? Or should I declare the vars inside of the function? Or even inside of the each-loop?

var $ytid = '',
    ytid = '';

function onYouTubePlayerReady() {

    $('object[id^="ytplayer_"]').each(function() {

        $ytid = $(this).attr('id');
        ytid = document.getElementById($ytid);

        ytid.addEventListener("onStateChange", "foo");

    });
};

I'm just curious what is better in this case and if I'm doing that correct right now? Thank you for your info and help?

Upvotes: 0

Views: 4359

Answers (2)

gor
gor

Reputation: 11658

Declaring variables at global scope is bad idea. Move them into function scope.

function onYouTubePlayerReady() {
    var $ytid = '', ytid = '';
    $('object[id^="ytplayer_"]').each(function() {
        $ytid = $(this).attr('id');
        ytid = document.getElementById($ytid);

        ytid.addEventListener("onStateChange", "foo");
    });
};

And you can get rid of them:

function onYouTubePlayerReady() {
    $('object[id^="ytplayer_"]').each(function() {
        this.addEventListener("onStateChange", "foo");
    });
};

Upvotes: 1

davin
davin

Reputation: 45525

Since the variables' values are unique to each iteration, you definitely need to define them inside the loop. Although you can make life a little easier for yourself and leave out the document.getElementById() call, since this is already pointing to the object you're looking for:

var ytid = this;
var $ytid = $(this).attr('id'); // only if you need the id for something other than instantiating the ytid variable

I used var as per gor's suggestion not to make the variables global

Upvotes: 1

Related Questions