문제

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();
도움이 되었습니까?

해결책

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();
    });
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top