javascript - removeEventListener, objects and this -
so, sounds trivial problem somehow i'm not quite sure how solve it.
here want accomplish :
function myobject() { //... } myobject.prototype.method1 = function() { document.addeventlistener("mousemove", this.method3, false); } myobject.prototype.method2 = function() { document.removeeventlistener("mousemove", this.method3, false); } myobject.prototype.method3 = function(e) { //... }
obviously doesn't work, because scope of "this" going wrong. usual prepare utilize anonymous function :
myobject.prototype.method1 = function() { var = this; document.addeventlistener("mousemove", function(e) {that.method3(e);}, false); }
but can't utilize removeeventlistener
what best way solve kind of stuff ? don't want utilize global variable intermediary function.
you pass along handler function method1
, method2
. after all, makes sense methods might want register other handlers too…
(changing name of functions create them more meaningful here)
function myobject() { //... } myobject.prototype.listenmouse = function(handler) { document.addeventlistener("mousemove", handler, false); } myobject.prototype.unlistenmouse = function(handler) { document.removeeventlistener("mousemove", handler, false); } myobject.prototype.standardmousehandler = function(e) { //... }
then:
var obj = new myobject(); obj.listenmouse(obj.standardmousehandler); // ... obj.unlistenmouse(obj.standardmousehandler);
javascript
No comments:
Post a Comment