JavaScript Developer
JavaScript Developer

Reputation: 4008

Firing Events in JavaScript

I have a JavaScript class named 'Item'. 'Item' is defined as shown here:

function Item() { this.create(); }
Item.prototype = {
  create: function () {
    this.data = {
      id: getNewID(),
    }
  },

  save: function() {
    $.ajax({
      url: getBackendUrl(),
      type: "POST",
      data: JSON.stringify(this.data),
      contentType: "application/json",
      success: save_Succeeded,
      error: save_Failed
    });
  },

  function save_Succeeded(result) {
    // Signal an event here that other JavaScript code can subscribe to.
  }

  function save_Failed(e1, e2, e3) {
    // Signal an event here that other JavaScript code can subscript to.
  }
}

Please note, I'm coming from a C# background. So I'm not even sure if what I want to accomplish is possible. But essentially, I want to create an object, subscribe to some event handlers, and attempt to save my object. For instance, I envision doing something like the following throughout my code.

var i = new Item();
i.item_save_succeeded = function() {
  // Do stuff when the item has successfully saved
};
i.item_save_failed = function() {
  // Do stuff when the item has failed to save
};
i.save();  // start the save process

Is this event-based approach even possible in JavaScript? If so, how? What am I missing? I keep getting a variety of errors that are vague. Because of that, I'm not sure if I'm getting closer or farther away.

Upvotes: 2

Views: 1149

Answers (2)

Sergio
Sergio

Reputation: 9917

Not 100% sure and I look forward to seeing the answer from a JS pro, but here is what I would do.

Expose some properties within you Item object - namely the functions you wish to be subscribed to.

Upon instancing an item you could then provide callback functions for the events that you wish to be notified of. In your code you could then do something like this:

    save: function() {
var self = this;    
$.ajax({
      url: getBackendUrl(),
      type: "POST",
      data: JSON.stringify(this.data),
      contentType: "application/json",
      success: function() { if(typeof(self.success) == "function") self.success(); }
      error: function() { if(typeof(self.fail) == "function") self.fail(); }
    });
  },

In effect, pass the callback functions to the object and let it call them directly when needed. I'm sure someone will now suggest a better way of doing it. :-)

Upvotes: 0

Călin Darie
Călin Darie

Reputation: 6237

If you are using jQuery, you can add an event handler to a custom event type. The following snippet is taken from the jQuery docs

$('#foo').bind('custom', function(event, param1, param2) {
  alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

But since jQuery 1.7 deprecates bind, you should use on now. See the jQuery docs for on.

Upvotes: 3

Related Questions