How to assign events in revealing prototype pattern?
-
10-04-2021 - |
Question
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();
Solution
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();
});
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow