Javascript Object Confusion

I embarrassed myself perfectly here. My scenario looks like this.

function DesignPad() {  
 function EditBar() {  
  ...  
  this.removeHandler = function() {  
    **// how do I call Dragger.removeAsset**  
  }  
 }  
 function Dragger(){  
  ...  
  this.removeAsset = function() {}  
 }  
 this.init = function() {  
  this.editBar = new EditBar();  
  this.dragger = new Dragger();  
 }  
}  

var dp = new DesignPad();  
...

      

I cannot call Dragag.RemoveAsset. I understand why, my question is: what should I call it?

I'm trying to split things up (Dragger / EditBar for example) but it looks like I have everything handled in event handlers. Any suggestions, good reading materials, etc. For this material?

Thanks.

+1


a source to share


4 answers


I found Douglas Crockford Javascript to be the best introduction to JavaScript. Especialy videos for Yahoo for example: JavaScript Programming Language where you can learn how exactly objects are created and inherited in JS.

Solution to your problem:



function DesignPad() {  
  var that = this;
 function EditBar() {  
  this.removeHandler = function() {  
    print("RemoveHandler");
    that.dragger.removeAsset();
  }  
 }  
 function Dragger() {  
  this.removeAsset = function() {
    print("RemoveAsset");
  }  
 }  
 this.init = function() {  
  this.editBar = new EditBar();  
  this.dragger = new Dragger();  
 }
}  

var dp = new DesignPad();
dp.init();
dp.editBar.removeHandler();

      

But as others have noticed, you can refactor some things :).

+3


a source


It seems to me that you should refactor this code to make it simpler.



I think your problem is because the nested function is private, so you cannot access it from the outside.

0


a source


Is the Dragger instance a "property" of your DesignPad object? If so, you can pass a reference to that object to your removeHandler () method.

0


a source


Try the following:

function DesignPad() {  

 function EditBar(s) {  
  super = s;
  this.removeHandler = function() {
    alert('call 1'); 
    super.dragger.removeAsset();  
  }  
 } 


 function Dragger(s){
  super = s;  
  this.removeAsset = function() {
      alert('call 2'); 
    }  
 }  

 this.init = function() {  
  this.editBar = new EditBar(this);  
  this.dragger = new Dragger(this);  
 }  

}  

var dp = new DesignPad(); 
dp.init()
dp.editBar.removeHandler();
alert('end');

      

0


a source







All Articles