Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout binding handler teardown function?

Tags:

I have a knockout binding handler that uses plupload for drag and drop and ajax uploads.

To use the plupload script I create an instance of plupload which in turn is binding event listeners to DOM elements.

That works fine.

However, I have a list of "folders" and when I click a folder I display a list of files in that folder. I reuse the same DOM elements for this by binding selectedFolder().documents using foreach.

The problem I have is that in my binding handler I do all my plupload stuff in the init function and since I reuse the DOM elements they get multiple event handlers bound to them. This causes the drag and drop events to be sent to alla handlers. This means that if I drop a file on the rendered file list, the drop event fires on all previously rendered file lists too.

What I am looking for is some sort of teardown or cleanup function in the binding handler, so that I can unregister all of the events whenever a file list get unrendered (is that a word?).

Maybe we cannot detect unrendering? How would I then handle this? I would prefer not to have a global instance, since that would prevent me from using the binding on multiple places at the same time.

Sorry about not giving you any code. I'm on my cell phone atm.

Cheers!

like image 475
Mikael Östberg Avatar asked Apr 25 '12 21:04

Mikael Östberg


1 Answers

You can register a handler that will be executed whenever KO removes elements (like when a template is re-rendered). It looks like:

    //handle disposal (if KO removes by the template binding)     ko.utils.domNodeDisposal.addDisposeCallback(element, function() {         $(element).datepicker("destroy");     }); 

So, in your "init" function you would register a dispose callback for the element that is being bound and you would have an opportunity to run whatever clean-up code that you would like.

like image 68
RP Niemeyer Avatar answered Oct 31 '22 20:10

RP Niemeyer