Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4324590
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T09:09:10+00:00 2026-05-21T09:09:10+00:00

I’ve written a short and incomplete example (for the sake of this question) that

  • 0

I’ve written a short and incomplete example (for the sake of this question) that attempts to use jquery to sum the width of a group of images. I’m having some issues figuring out how to handle scope in complex OO javascript applications.

function imageContainer(){
      this.selector = "img.inContainer";

      this.width = function(){
        var tmp = 0;
        $(this.selector).each(function(){
          // use load to preload images
          $(this).load(function(){ 
             // our 'this' pointer to the original object is long gone,
             // so is it even possible to accumulate a sum without using
             // globals? Ideally, I'd like to increment a temporary value
             // that exists within the scope of this.width();
             tmp+=$(this).width();
          });
        });
        // I'm thinking that returning here is problematic, because our
        // call to each() may not be complete?
        return tmp;
      }

      this.construct = function(){
        alert(this.width());
      }

      this.construct();
}

I’m not really looking for a hack around this issue, I’d like to know how this sort of thing should be done – in a way that doesn’t trash encapsulation. Am I missing something obvious?

Many thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T09:09:11+00:00Added an answer on May 21, 2026 at 9:09 am
    function imageContainer() {
        this.selector = "img.inContainer";
    
        this.width = function(cb) {
            var tmp = 0;
            var len = this.length;
            var count = 0;
            $(this.selector).each(function() {
                // use load to preload images
                var that = this;
                // load is ajax so it is async
                $(this).load(function() {
                    tmp += $(that).width();
                    if (++count === len) {
                        // counted all.
                        cb(tmp);
                    }
                });
            });
        };
    
        this.construct = function(cb) {
            this.width(function(data) {
                alert(data);
            });
        };
    
        this.construct();
    }
    

    Welcome to ajax. Your doing a bunch of operations in parallel asynchronously. So you need to keep track of how many complete and fire a callback when all have completed.

    Any asynchronous operation like .load requires you to either block for 100s of ms or change your API to use callbacks.

    Rather then the var that = this pattern you can also use $.proxy instead.

    // load is ajax so it is async
    $(this).load($.proxy(function() {
        tmp += $(this).width();
        if (++count === len) {
            // counted all.
            cb(tmp);
        }
    }, this));
    

    Since you have the construct of doing n ajax tasks before firing your callback you can generalize this with some sugar.

    this.width = function(cb) {
        // map all images to deferred objects, when deferred objects are resolved
        $.when($.makeArray($(this.selector).map(function() {
            var def = $.Deferred();
            $(this).load(function() {
                def.resolve();
            });
            return def;
        // then sum the widths and fire the callback.
        }))).then($.proxy(function(data) {
            var tmp = 0;
            $(this.selector).each(function() {
                 tmp+=$(this).width();
            });
            cb(tmp);
        }, this));
    };
    

    Notice here I really want to use $.fn.reduce but it does not exist. It could have been

    // reduce the set of images to the sum of their widths.
    cb($(this.selector).reduce(0, function(memo, key, val) {
        return memo + $(this).width();
    }));
    

    On second thought this sugar does not make it any simpler, at least it looks more like LISP then C now.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
I have a jquery bug and I've been looking for hours now, I can't
this is what i have right now Drawing an RSS feed into the php,
I've got a string that has curly quotes in it. I'd like to replace
I am reading a book about Javascript and jQuery and using one of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.