Skip to content Skip to sidebar Skip to footer

Sending Data From Classes?

I'm looking into deferred and custom events. I'm not sure what method would suit my application. I have a class that calls another class. Inside this class a user can drag files on

Solution 1:

There are typically two options for this:

Delegate

A delegate should implement a certain "interface", a set of functions that handle certain events.

functionDropBox(delegate)
{
    this.delegate = delegate;

    $(window).on('drop', $.proxy(this, 'drop'));
}

DropBox.prototype.drop = function(e) {
    // do stuff with eventthis.delegate.drop(e);
}

// inside main instancethis.dropBox = newDropBox(this);
// delegate interfacethis.drop = function(e) {
    // handle file drop
};

Callback

If the delegate only needs one function, you can use a callback as well:

functionDropBox(dropEventHandler)
{
    this.dropEventHandler = dropEventHandler;
    $(window).on('drop', this.drop);
}

DropBox.prototype.drop = function(e) {
    this.dropEventHandler(e);
};

// inside main instancevar self = this;
this.dropBox = newDropBox(function(e) {
    // handle file drop// use 'self' to reference this instance
});

Solution 2:

Why not just give a callback over to the DropBox?

Well, like this code in the main class:

this.dropBox = newDropBox(function(fileInfo) {
  // this code can be executed by the DropBox Object multiple times!
});

And the DropBox:

window.DropBox = function(callback) {
  this.userHasDroppedFiles = function(fileinfo) {
    // do stuffcallback(fileinfo); // give the fileinfo back with the callback!
  }
}

Also, there are no classes in JavaScript! You have only Objects, and you can use constructor-functions combined with prototypes to generate a class like behaviour, but you will never actually have classes like in Java, C# or similar languages. Keep this always in mind. Some JS frameworks build their own class layer on top of the main JS possibilities, then you may have Framework classes, but also nevernative JavaScript classes, because native JavaScript classes dont exist!

Post a Comment for "Sending Data From Classes?"