-4

I have a class that calls another class.

Using jquery .on() how can I listen for events taking place in the child class, from the parent class.

I'm aware that there are no classes in javascript, I have set it up via prototyping.

This is what I have but I get:

Uncaught TypeError: undefined is not a function 

Here's the code:

this.fileDrop = new lp.FileDrop();

this.on("test", function(){alert('a'});

Here's my class:

(function () {
    "use strict";

    var Loon = function () {
        this.init();
    };

    p.init = function () {
        this.fileDrop = new lp.FileDrop();

        this.on("test", function () {
            console.log('a')
        });
    };

    lp.Loon = Loon;
}(window));

var loon;

$(function () {
    loon = new lp.Loon();
});
isherwood
  • 58,414
  • 16
  • 114
  • 157

1 Answers1

1

I've seen roughly the same question come back a couple of times now, it's already answered by Jack a while ago but he forgot to use bind in his examples so this is not resolved as you'd like it to be. Hope the following helps a bit:

function DropBox(mainClassInstance){
  this.delegate=mainClassInstance;
  $(document.body).on("click",this.drop.bind(this));
}
DropBox.prototype.drop=function(e){
  console.log("window event triggered in dropbox instance");
  this.delegate.drop(e);
}

function MainClass(){
  this.dropBox=new DropBox(this);
}
MainClass.prototype.drop=function(){
  console.log("drop in mainclass, dropbox is:",this.dropBox);
}
var m = new MainClass();

The following answer may help you out with creating objects in JavaScript: https://stackoverflow.com/a/16063711/1641941

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160