SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Sep 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question object property problem

    hi all,

    i'm buliding an image slider object with the following code:

    1. function imageGalery(index, width){
    2. ...
    3. this.isScrolling = false;
    4. ...
    5. this.startScroll = function(){
    6. if(this.isScrolling == false){
    7. this.isScrolling = setInterval('galery'+index+'.scroll();',30);
    8. }
    9. }
    10. this.stopScroll = function(){
    11. clearInterval(this.isScrolling);
    12. this.isScrolling = false;
    13. }
    14. ...
    15. img = document.createElement('img');
    16. img.onmouseover = this.startScroll;
    17. img.onmouseout = this.stopScroll;
    18. ...
    19. }


    the thing is that it start scrolling only on the second time i hover the img...

    i'm guessing it's because the stopScroll method was already launched but i don't understand why declaring the property isn't enough.

    i have also manged to bypass it by writing "eval('galery'+index)" (the object's name) instead of "this" on line 6. can someone explain?

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    this is no longer the same inside the function. The nested function creates a new closure, and therefore creates a new sort of "environment" that has its own this. So to avoid this, you have to make a copy of the original this.

    Code javascript:
    function imageGalery(index, width) {
      this.isScrolling = false;
      var gal = this;
      this.startScroll = function() {
        if (!gal.isScrolling) {
          gal.isScrolling = setInterval('galery'+index+'.scroll();',30);
        }
      }
    }

    The stuff inside the setInterval looks very suspicious. It looks like you're making lots of differently named functions that do the same thing. Can't they all be merged into a single function that takes an argument?

  3. #3
    SitePoint Member
    Join Date
    Sep 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Smile

    that was quick!
    thank u, storing 'this' will sure be helpful.
    regarding the setInterval, i'll check myself...

    thanx again!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •