custom callback on jquery event - javascript

I am working with jquery and jstree
I have an event that triggers every time my tree changes:
$tree.jstree()
.on("changed.jstree", function(event, target) {
//manipulate data
});
It works perfect. I can access "this" (the tree), and also event and target. But, I am trying to define a custom callback. I tried something like this:
window.customCallback = (function(event, target) {
//manipulate data
//$(this).foo() manipulates the tree
//event.type to access the event type
//target.node to access the node
}(this));
So I can use:
$tree.jstree()
.on("changed.jstree", customCallback(event, target));
But it doesn't work. Could somebody help me out?

$tree.jstree().on("changed.jstree", customCallback(event, target));
What you're doing is setting the result of customCallback as callback handler.
What you want to do is set the function itself as callback handler:
var customCallback = function(event, target) {
// ...
};
$tree.jstree().on("changed.jstree", customCallback);
Notice the "missing" brackets - because brackets would invoke the function and we don't want that.
The parameters will be passed to the handler automatically.

Related

Using "this" as parameter in an existing Javascript function called by jQuery.on() event

Problem:
I have some selects with options in my HTML code and I have set an on change event handler, to figure out, when a selection will be changed.
The following code shows the jQuery code to get the on change:
$(document).on('change', '.anyHtmlSelect', updateState);
I have an existing Javascript function, that should be used as callback function.
The Javascript function looks like:
function updateState(element)
{
var currentId = element.attr("id");
}
Question:
How can I get the changed select as element?
I have tried the following:
$(document).on('change', '.anyHtmlSelect', updateState($(this));
but it doesn't work.
The first argument that is automatically passed to an event handler is a reference to the event itself, not the element that caused the event. To access the DOM element that triggered the event, use this:
Simply change:
function updateState(element)
{
var currentId = element.attr("id");
}
to:
function updateState(event) {
var currentId = this.attr("id");
}
After some research I have found a solution I would share with you.
In my solution, I created an anonymous function, which calls the updateState function with $(this) as parameter.
$(document).on('change', '.anyHtmlSelect', function () {
updateState($(this));
});
Is there a better solution?

How to access $(this) and event in defined callback function

I'm trying to enable some touch controls through a callback function but I'm having trouble accessing the event as well as $(this) in my callback function. Right now the code looks as follows:
$('.img-responsive').each(touchControls);
function touchControls(event) {
event.preventDefault();
var mc = new Hammer(this);
mc.on("doubletap", function() {
console.log($(this));
});
}
Where '.img-responsive' is a class of images on my page.
When it tries to call event.preventDefault, I get an error that event.preventDefault is not a function. I thought the event was automatically passed to the variable called? I know when I did a named callback function with .on, event.preventDefault() worked perfectly fine. I assume it's different when I do it with .each, how do I properly access it?
Now, if I remove the event.preventDefault() line, when it logs $(this), I get a function. I was expecting to get individual elements so I could set touch controls for them, but that clearly didn't work. I tried to bind 'this' by:
$('.img-responsive').each(touchControls).bind(this);
But when I logged $(this), it was still a function and not the element I was expecting.
I'm basically just confused as to how to access $(this) and event within the defined callback function.
.each is not an event handler so its callback function does not accept an event object. The method signature of the each callback function looks like this:
.each( function )
function
Type: Function( Integer index, Element element )
A function to execute for each matched element.
So you won't have an event object to reference but, more importantly, there will be no default event behavior to prevent.
Conversely, on does in fact setup event handlers. Its callback function does take an event as its parameter. You can handle your event management within your event handler code, inside the callback function for .on.
this will refer to your current element as you iterate. But inside your inner callback function there will be a different context (so a different this). Simply store a reference to the element in the outer scope:
function touchControls() {
var $this = $(this);
var mc = new Hammer(this);
mc.on("doubletap", function(e) {
e.preventDefault();
console.log($this);
});
}
You have the event being passed in the wrong function.. You need to pass it into the event listener. The first argument of an each loop is the current index of the iteration.
$('.img-responsive').each(touchControls);
function touchControls(eachIndex) {
var mc = new Hammer(this);
mc.on("doubletap", function(event) {
// move preventDefault here and pass the event
event.preventDefault();
console.log($(this));
});
}
function Hammer(el){
return $(el)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="img-responsive">img</div>
<div class="img-responsive">img</div>

Using $(this) & event in named handler function

I have this function:
function showPost(event){
event.preventDefault();
$(this).parent('article').animate({width:'100%'}, 'slow');
}
I am attempting to use it like so:
$('.article-header').click(function(event){showPost(event);});
When I use it in the above manner, the event property is passed just fine, however $(this) doesn't work within the function. If I attempt to include this as a parameter in the .click method, it returns an error claiming this is undefined. I have even gone so far as to set var ths = $(this); to no avail.
Please, what is the proper way to make this function happen?
Just use the function directly:
$('.article-header').click(showPost);
You're loosing this because you're calling the function "naked", with no object receiver. You could do this too (but don't because there's no point here):
$('.article-header').click(function(event) { showPost.call(this, event); });

What is passed with the bind in JS?

I am binding a select of a custom control to a function. I just want to clarify when I bind something like this
auditFileUpload.bind("select", uploadSelectfunction);
I know I can use the following function
uploadSelectfunction(e)
{
}
how is e getting passed? is it the events? or the object itself?
if I had a function like this, how would I bind it?
uploadSelectfunction(e, datatype)
{
}
auditFileUpload.bind("select", function() { uploadSelectfunction(events, "CSV" });
I tried events, it doesn't work..
sugesstions? clarifications?
The events parameter is simply the first parameter passed to the event handler/method. Just pass that on:
auditFileUpload.bind("select", function(events) { uploadSelectfunction(events, "CSV"
In the original version uploadSelectfunction is simply a pointer to a function that happens to take one argument. That events argument is defined inside the select event.
If you put an inline method instead (as you have done) you need to accept the events parameter, and pass it on to your code.

Check event target when using document.attachEvent

I have the following code...
document.attachEvent("onclick", get_func(obj, "on_body_click", "event_target_here"));
I am attaching a global function get_func() to the event onclick. get_func() returns reference to a function defined in a function object something like this..
function get_func(obj, funcname, params) {
if(funcname == "check") {
return obj.checkTarget(params);
}
}
Now in the function checkTarget(), I need to check which DOM object was clicked upon. How can I do this? I understand that I need to send the target of onclick event to the global function somehow.
Can somebody throw some light on this?
Regards
If you want to pass the object that was clicked on into the global function, you can modify your event attachment to use the click event's source element to something like this:
document.attachEvent("onclick", function(e) { get_func((e || event).srcElement, "on_body_click", "event_target_here") });
Then you could pass that object down to the checkTarget function.

Categories

Resources