1

I am trying to implement Revealing Module Pattern. I need to assign an event handler to one of elements, this event handler is a function I define in protoype but I get this.trigger is not a function error.

Here's what I have done:

//constructor
var MyClass = function (settings) {
   this.someElement=$(settings.elementID);
}

//prototype    
MyClass.prototype = function() {
    var init = function() {
        this.someElement.change(this.handler);
    },
        handler = function() {
        this.someElement.hide();
    };

    return {
        init : init,
        handler : handler
    };
}();

Here's how I call it:

var myClass = new MyClass();
myClass.init();
Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
  • 2
    I don't see where the `this.trigger` is comming from. – hugomg Dec 30 '11 at 23:48
  • I am trying to do something with this.someElement in handler. Is that a problem with closure? – Ufuk Hacıoğulları Dec 31 '11 at 12:35
  • one issue I see is that within MyClass.prototype, handler is not being scoped correctly. without "var" it is being declared globally, which you probably don't want. Probably not the issue, but you should fix it nonetheless. So are you trying to call handler from a "new" instance? You should also post the code that is calling this method. – thescientist Dec 31 '11 at 12:43
  • @thescientist It has a var clause from the previous declaration. Notice the ',' – Ufuk Hacıoğulları Dec 31 '11 at 12:49
  • I don't understand some people's insistenance on `var a, b, c` when spread over separate lines - I much prefer `var a; var b;` and find it far less error prone. – Alnitak Dec 31 '11 at 13:22

1 Answers1

1

I guess your constructor should be

var MyClass = function (settings) {
    this.someElement = jQuery("#" + settings.elementID);
}

Then you will be able to call jQuerys trigger method on that element with (new MyClass({elementID:"someid"})).someElement.trigger(), because "trigger" is a method of the jQuery instance which is the "someElement" property of your object.

Also, your handler won't work because it is called in context of the element, not of your object. So it should be

MyClass.prototype.init = function init() {
    this.someElement.change(this.handler || function defaulthandler() {
        $(this).hide();
    });
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375