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.

function DropBox(delegate)
{
    this.delegate = delegate;

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

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

// inside main instance
this.dropBox = new DropBox(this);
// delegate interface
this.drop = function(e) {
    // handle file drop
};

Callback

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

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

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

// inside main instance
var self = this;
this.dropBox = new DropBox(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 = new DropBox(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 stuff
    callback(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 never native JavaScript classes, because native JavaScript classes dont exist!


Post a Comment for "Sending Data From Classes?"