JQuery attach event to method in instance - javascript

I have code that looks like this....
function Finder(id) {
this.id = id;
this.input = $("#" + this.id + " :input[type='text']:first")[0];
$(this.input).bind('keyup'....);
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
this.input = the 1st element of type input found within 'id' which is what I will be referencing. This works fine for what I need.
What I want to do then is to bind the keyup event on 'input'. However I want the event to reference the instance method contained in my function - this.KeyUpHandler().
Also I need 'e' to be event that would have been passed into the function had I just done this on the markup for the input (onkeypress="keyuphandler();").
Any ideas how I can bind the event to the a function in the instance of the function I am working within?

function Finder(id) {
this.id = id;
this.input = $("#" + this.id + " :input[type='text']:first")[0];
that=this;
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
$(this.input).bind('keyup', this.KeyUpHandler);
}
It is important that you call bind() after defining the function!

this.KeyUpHandler = function (e) { ..the event should trigger this.. }
$(this.input).bind('keyup', function(){
this.KeyUpHandler(event);
//more code can go here
});

Related

Passing this to a method?

p.num = 100;
$('body').on('click', '.del', this.delete.bind(this));
p.delete = function(e) {
console.log(this.num); //100
//how can I get the .del element?
}
I'm trying to get the element that produced the click, but I also need access to the num property.
How can I access both types of 'this' inside my delete method?
The callback for an event receives an Event object that you can use to retrieve the element on which the event was called.
function(e) {
var element = $(e.target); //This is the element that the event was called on.
}
Disclaimer : This is the my exact answer (adapted with the current code) taken from here : Pass additional arguments to event handler?
Yet, the question doesn't seem to be an exact duplicate (but i may be wrong).
As said in the documentation of .on, you can pass datas to your event.
.on( events [, selector ] [, data ], handler )
data
Type: Anything
Data to be passed to the handler in event.data when an event is triggered.
So your event could look like that :
p.num = 100;
$('body').on('click', '.del', {object : this}, this.delete);
p.delete = function(e) {
var myObj = e.data.object;
// [myObj] will be your plugin
// [this] will be the clicked element
// [e] will be you event
}
if you're using jquery, you can combine those functions all into one like below:
note: num is an attribute so you have to use .attr().
$(document).ready(function() {
$('body').on('click', '.del', function() {
var num = $(this).attr('num');
alert('click function and num = ' + num);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Delete
or if you really want to keep them separate functions....:
$(document).ready(function() {
$('.del').on('click', function() {
deleteThis($(this));
});
});
function deleteThis(element){
var num = element.attr('num');
alert('click function and num = ' + num);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Delete
also, if youre using separate functions for the click and the delete, pass the element from click to delete: pass element - callDeleteFunction($(this)), and retrieve element - myDeleteFunction(element aka $(this))
I'm not sure what you're asking about but maybe this is what you want:
var p = {};
p.num = 100;
$('body').on('click', '.del', p.delete); // don't bind to this
p.delete = function(e) {
console.log(p.num); // here you still can call p
// this is del DOM element
}

jquery bind data to click event for object created dynamically

Script below create button and event dynamically. I want to bind data to click event. But bind() function failed, click event just won't trigger. Anyway, click event successfully triggered if I'm using on() function.
http://jsfiddle.net/hzLv1r6s/2/
function showMessage(evt) {
alert(evt.data.message);
}
$(document).ready(function () {
var activeDiv;
var pVar = { message:'Hello from a paragraph'};
$("a").on("click", function () {
if (activeDiv === $(this).attr('id')) {
$('#__div').hide('slow');
activeDiv = '';
return;
}
$('.box1').empty();
var guts =
'<div id="__div" style="display:none;">' +
'<input type="text" id="__text" value="' + $(this).attr('data-content') + '"/><br>' +
'<button id="__internal" value="aaa">Submit</button>' +
'</div>';
//this one doesn't work on click event
$('#__internal').bind('click',pVar,showMessage);
$($.trim(guts)).appendTo('.box1');
$('#__div').show('slow');
activeDiv = ($(this).attr('id'));
});
/*
//this one does work on click event
$('.box1').on('click','#__internal',function(event){
//alert(event.target.value);
alert($('#__text').val());
});
*/
});
You need to use event delegation at this context,
$('.box1').on('click','#__internal' , showMessage);
Or try to bind the event to it after that html string got appended into the DOM.
$($.trim(guts)).appendTo('.box1');
$('#__internal').bind('click',pVar,showMessage);
NOTE: But i don't know why are you refusing to use event delegation here.
DEMO created without event delegation.

How to avoid multiple function call

I have click event function to create a new dom elements. Basically, every time I click a button. It allows create a new hyperlink tag.
I also want to have a functionality that if new created hyperlink clicked, I want to call different function.
Please have a look following code,
var id = 1;
$('#create').on('click', function() {
id ++
$('.players').append('<a href="#" class="new" data-id='+ id + '> ' + id + 'player</a>');
getId()
});
function getId() {
$('.new').on('click', function() {
var id = $(this).data('id')
alert(id);
});
}
My problem is I don't want to run getId() function everytime I clicked a button, But if I run getId() function alone, new created hyperlink won't effent that functionality.
Is anyway I can call getId() function once. and It still going to effect a new created hyperlink?
You can use one method to use the function only for once.
function getId() {
$('.new').one('click', function() {
var id = $(this).data('id')
alert(id);
});
Use delegation, then there is no need to attach the event handler function every time you append. Remove your getId() function and replace it with a delegated on() method:
var id = 1;
$('#create').on('click', function () {
id++;
$('.players').append('<a href="#" class="new" data-id=' + id + '> ' + id + 'player</a>');
});
$('.players').on('click', '.new', function(e) {
e.preventDefault();
var id = $(this).data('id')
alert(id);
});
JSFiddle
Try to use on() for dynamic elements like,
$(function(){
var id = 1;
$('#create').on('click', function() {
id ++;
$('.players').append('<a href="#" class="new" data-id='+id+'>'+id+'player</a>');
});
$(document).on('click','.new', function() {
//use ^ document or your parent element players
var id = $(this).data('id');
alert(id);
});
});

Create javascript object with event handler

I have created a JavaScript Object and named it 'Button'. this object has a function that draw a button and append it to specific div element.
var Button = function (id, value) {
this.id = id;
this.value = value;
this.draw = function () {
var element = document.createElement("input");
element.type = "button";
element.id = id;
element.value = value;
document.getElementById("topDiv").appendChild(element);
}
};
I instantiate Button object and call draw() function like this:
var myButton = new Button('btn1', "Test Button");
myButton.draw();
My problem is I cant handle events. I want to connect onclick event to a function. for example:
myButton.onClick = function(){ alert(1); };
but I don't know how to define this.
Try
var Button = function (id, value) {
this.id = id;
this.value = value;
this.draw = function () {
this.element = document.createElement("input");
this.element.type = "button";
this.element.id = id;
this.element.value = value;
document.getElementById("topDiv").appendChild(this.element);
}
};
Button.prototype.addEventListener = function(event, handler){
var el = this.element;
if(!el){
throw 'Not yet rendered';
}
if (el.addEventListener){
el.addEventListener(event, handler, false);
} else if (el.attachEvent){
el.attachEvent('on' + event, handler);
}
}
Demo: Fiddle
I know it's an old question but it's worth mentioning that you could have done it after appending to div:
document.getElementById("topDiv").appendChild(element);
this.element.onclick = function(){ alert(1);};
this is more consistent and much less coding.
jsfiddle
You would have to create your own click() method (which takes a function as a parameter) that binds to the DOM element's click handler. Your draw() method can store a reference to the element in the object instance so that your click() method can access it.
As it was already mentioned, you should attach events to DOM objects.
The simple way is just to expose your DOM element from your custom class:
var Button = function (id, value) {
this.id = id;
this.value = value;
var element = document.createElement("input");
this.element = element;
this.draw = function () {
element.type = "button";
element.id = id;
element.value = value;
document.getElementById("topDiv").appendChild(element);
}
};
Now you can:
var myButton = new Button('btn1', "Test Button");
myButton.draw();
myButton.element.onclick = function(){ alert(1); };
If Native Javascript....
document.getElementById("btn1").onclick
If jQuery
$('#btn1').click(//function(){})....
If jQuery but Button is Created dynamically....
You might try..
$('#btn1').live('click',//function(){ })....
EDIT: As Suggested in the Comment:
Please read what the Documentation says:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to
attach event handlers. Users of older versions of jQuery should use
.delegate() in preference to .live().
This method provides a means to attach delegated event handlers to the
document element of a page, which simplifies the use of event handlers
when content is dynamically added to a page. See the discussion of
direct versus delegated events in the .on() method for more
information.
Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
ADDITIONAL
If You can't live without -live-...
As of jQuery 1.4 the .live() method supports custom events as well as
all JavaScript events that bubble. It also supports certain events
that don't bubble, including change, submit, focus and blur.

jQuery - using $(this) in custom function

I'm trying to create a custom function that unbinds and then binds an event. It looks like this:
App.bindEvent = function(selector, eventType, eventHandler) {
$(selector).unbind(eventType);
$(selector).bind(eventType, function(event) {
eventHandler(event);
});
};
However, the problem I am facing is that I cannot use the this keyword to reference the DOM element that was clicked. For example, I cannot do this:
App.bindEvent("#my-element", "click", function() {
var myId = $(this).attr("data-my-id");
});
How would I go about getting the this keyword to point to the clicked DOM element like it does in jQuery.bind()?
Thanks for any help.
Change:
eventHandler(event);
To:
eventHandler.call(this, event);
That'll change the "scope" of your function to be the same as the scope of the original "bind" call.
How about this instead:
App.bindEvent = function(selector, eventType, eventHandler) {
var element = this;
$(selector).unbind(eventType);
$(selector).bind(eventType, function(event) {
eventHandler.call(element, event);
});
};
You need to call the handler in the context of the object:
eventHandler.call(this, event);
I think you're trying to refer to
event.target
For example:
App.bindEvent("#my-element", "click", function(event) {
var myId = $(event.target).attr("data-my-id");
});
check out jquery's event documentation

Categories