www.webdeveloper.com
Results 1 to 3 of 3

Thread: How do i provide context to "this" for an onload callback without using bind?

  1. #1
    Join Date
    May 2012
    Posts
    9

    How do i provide context to "this" for an onload callback without using bind?

    How do i provide context to "this" for an onload callback without using bind?
    HTML Code:
    function App()
    {
    	this.count = 10;
    	this.img = new Array();
    }
    
    App.prototype.init = function()
    {
    	this.img[0] = this.registerImg("resources/1.jpg");
    	this.img[1] = this.registerImg("resources/2.jpg");
    	this.img[2] = this.registerImg("resources/3.jpg");
    }
    
    App.prototype.registerImg = function(uri)
    {
    	var img = new Image();
    	img.onload = function() //how do i set "this" to the object of my choice?
    	{
    		this.doSomething();
    		this.count++;
    	}
    	img.src = uri;
    }
    
    App.prototype.doSomething = function()
    {
    	alert(this.count);
    }
    
    var app = new App();
    window.onload = app.init;
    it's fairly obvious that i can just hardcode the callback as follows:
    HTML Code:
    App.prototype.registerImg = function(uri)
    {
    	var img = new Image();
    	img.onload = function()
    	{
    		app.doSomething();
    		app.count++;
    	}
    	img.src = uri;
    }
    but, this would similar to simply binding the function to the app object. Is there a way to dynamically "bind" that onload callback?
    Last edited by rainstorm; 06-17-2012 at 01:16 PM.

  2. #2
    Join Date
    May 2012
    Posts
    9
    Sorry for double posting, but i discovered something peculiar.

    HTML Code:
    App.prototype.registerImg = function(uri)
    {
    	var img = new Image();
    	img.onload = function()
    	{
    		alert(app.count+" "+uri);
    		app.doSomething();
    		app.count++;
    	}
    	img.src = uri;
    }
    I was expecting to get the alert message:
    0 undefined
    1 undefined
    2 undefined

    instead i got (in no particular order):
    0 resources/1.jpg
    0 resources/2.jpg
    0 resources/3.jpg

    How is the callback accessing the uri argument? Yet, when i replace "app.doSomething()" with "this.doSomething()" it's unable to determine that "that" should be the app object.

  3. #3
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Code:
    App.prototype.registerImg = function(uri){
       var that=this;
    	var img = new Image();
    	img.onload = function()
    	{
    		alert(this.count+" "+uri);
    		this.doSomething();
    		this.count++;
    	}
    	img.src = uri;
    }

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles