Reputation: 4733
I have attached a click event of span in this way. The span is within a table.
$("#tblImport").find("span").each(function () {
$(this).click(function () {
appendData(this);
});
});
This event handler "appendData" makes an ajax request and gets the data.
function appendData(prntSpan) {
$(prntSpan).append(createElements());//ajax call.
updateEvents(prntSpan);
}
What I want is to detach this click event handler and attach a new one. So I tried this.
function updateEvents(curntSpan) {
$(curntSpan).off('click');//this works
$(curntSpan).off('click', appendData);// but this does not work strange
$(curntSpan).on('click', toggleData(curntSpan));//nor a new click handler is attached
}
The function is called when the above line where .on is used is executed, but afterwards when you click on the span no event is fired.
Upvotes: 0
Views: 1641
Reputation: 7445
You have wrong syntax in .on()
function check it. So In my opinion you should change your code for:
$("#tblImport span").click(function (e) {
e.stopPropagation();
appendData(this);
});
this has cleaner syntax.
function updateEvents(curntSpan) {
$(curntSpan).off('click');//this works
$("#tblImport").on('click', curntSpan, function() { toggleData(curntSpan); });
}
Upvotes: 2
Reputation: 7837
function updateEvents(curntSpan) {
/* ... */
$(curntSpan).on('click', toggleData(curntSpan));
}
What this will do is this:
$(curntSpan)
, yielding a jQuery object.on
attribute'click'
and toggleData(curntSpan)
, yielding a string and something else.on
attribute with the string and the something else from the previous step as argumentsI think what you want instead is something like this:
function updateEvents(curntSpan) {
/* ... */
$(curntSpan).on('click', function(){ toggleData(curntSpan) });
}
In step 3, this will evaluate function(){ toggleData(curntSpan) }
instead of toggleData(curntSpan)
—the result being a function that calls toggleData(curntSpan)
when called (i.e. when the click
event is fired).
The general rules:
f(x)
, you run the function and take the resultfunction() { /* f(x) */ }
, the result is simply that function (here: one that takes no arguments and which has an empty body, due to it being commented out).The same logic is why you do $(function() { /* ... */ })
rather than $(f(x))
to have some code run when the page has been "booted".
Upvotes: 1
Reputation: 1985
$(curntSpan).off('click', appendData);
will not work as you don't put appendData as handler at the first place.Into handler you put anonymous function within you run appendData, but not appendData itself
Upvotes: 0