Zikes
Zikes

Reputation: 5886

Inheriting jQuery's Events Model

I'm developing an SDK for a site API which depends on jQuery and I'd like to utilize jQuery's custom events model within the SDK. How can I best inherit, wrap, or otherwise utilize jQuery's events without requiring an arbitrary DOM element to attach them to?

Current basic structure is below:

;(function($, global, undefined){

  function MySDK(opts){

  }

  MySDK.prototype.on = function(evt, fn){};
  MySDK.prototype.trigger = function(evt, data){};

  if(global.MySDK){
    throw new Error("MySDK has already been defined");
  }else{
    global.MySDK = MySDK;
  }
})(jQuery, typeof window === "undefined" ? this : window);

Upvotes: 0

Views: 444

Answers (1)

T. Stone
T. Stone

Reputation: 19495

You can attach the events and listeners to the window object.

Example:

MySDK.prototype.trigger = function(evt, data) {
    $(window).trigger(evt, data);
};

If you're writing javascript for others to consume, I'd also strongly recommend you look into sandboxing your framework by running it inside of a src-less iframe. All the better if each version SDK has it's own iframe.

Upvotes: 1

Related Questions