Get prototype inside an eventhandler
I'm trying to get the prototype inside an event handler.
function Post(){
this.post;
this.deleteButton;
}
Post.prototype.delete = function(){
var OBJ = this;//this is not the prototype, instead it is the HTML element (deleteButton)
开发者_JAVA百科$(OBJ.container).remove();
}
Post.prototype.createPost = function(){
var OBJ = this;
OBJ.post = document.createElement('div');
OBJ.post.className = 'post'
OBJ.deleteButton = document.createElement('div');
OBJ.deleteButton.addEventListener('click', OBJ.delete, false);
}
Look at the comment section above. A delete handler is declared as a prototype method to Post
. And I assign the delete handler to a delete button. The thing is that this
becomes the HTML Element instead of the object prototype.
EDIT:
I also want to have the opportunity to remove the delete handler
Like this:
OBJ.deleteButton.addEventListener('click', function() {
OBJ.delete();
}, false);
But OBJ
is not the prototype, it refers to the instance.
Update: If you want to remove it too, store a reference to it:
this.deleteHandler_ = function() {
OBJ.delete();
};
OBJ.deleteButton.addEventListener('click', this.deleteHandler_, false);
Somewhere else:
this.deleteButton.removeEventListener('click', this.deleteHandler_);
In jQuery you can use $.proxy:
var onDelete = $.proxy(OBJ.delete, OBJ);
OBJ.deleteButton.addEventListener('click', onDelete, false);
There's also ECMAScript 5 bind method:
var onDelete = OBJ.delete.bind(OBJ);
OBJ.deleteButton.addEventListener('click', onDelete, false);
To remove the listener:
OBJ.deleteButton.removeEventListener('click', onDelete, false);
Post.prototype.createPost = function(){
var OBJ = this;
OBJ.post = document.createElement('div');
OBJ.post.className = 'post'
OBJ.deleteButton = document.createElement('div');
OBJ.deleteButton.addEventListener('click', function(){OBJ.delete();}, false);
}
If you are using jquery you can use the proxy method:
OBJ.deleteButton.addEventListener('click',$.proxy(OBJ.delete,OBJ), false);
精彩评论