Search code examples
jqueryeventsbindingclone

How to rebind an event with new parameters after clone()?


I'm creating a toggle button with this function: http://pastebin.com/gLkeB7pi Then I'm cloning this toggle button for a similar use - but not exactly the same. For that purpose, I need the same 'click' behaviour (that is, select/unselect & checkbox) but on the new cloned button.

So I'm trying this: First, I modified createToggleButton: http://pastebin.com/tFZVafwE Basically, I passed a checkbox parameter to the click handler by event.data and I modified the internal functions consequently, so that the new toggle checkbox is checked. Then I did this:

var toggle = toggleButton.clone(true); //toggleButton is the toggle inside the div created with createToggleButton()
$(toggle).unbind('click');
$(toggle).bind('click',
    {chkbx: $(toggle).find('input[type=checkbox]')},
    function(evt){toggle.toggle(evt)}
);

But then, I can't figure out at all what happens. On click, the new toggle slides up (?!) and the toggle.toggle function is not executed at all (I added a console.log). So:

1) Am I thinking the right way to do what I wanna do?

2) Which code is actually executed on click and why?


Solution

  • Okay I got it. In case anyone stumble upon the same kind of problem:

    First - hacky and not tested - solution: if you want (or need) to use clone, first note that a JS Object method called toggle already exists. That was the one being called in my case, instead of the toggle.toggle I created. Moreover, the methods created in my createToggleButton function are not copied with clone. So, as David said, it's better binding with $._data( toggleButton[0], 'events' ).click[0].handler;. Even then, in my case it won't work because toggle.toggle calls toggle.active or toggle.deactive which both don't exist in this context. So it's necessary not to call any side function in the handler.

    Second solution (better): Don't use clone. Reuse createToggleButton and manually add the needed HTML attributes (see jQuery: How to copy all the attributes of one element and apply them to another?).