Use jQuery Deferred inside plugin to always call cleanup method -
Use jQuery Deferred inside plugin to always call cleanup method -
i'm writing jquery ui plugin. within plugin, when action occurs, i'm invoking 1 of plugin options callback. 1 time callback completed, want run cleanup code.
to more specific, plugin uses jquery ui draggable , droppable. on droppable drop, invoke function defined in options called update. after update called, ajax call, want perform cleanup. don't want user of plugin required perform cleanup call; want cleanup phone call happen automatically after update ajax method successful.
i thought using jquery's deferred made sense here. here's code plugin's drop implementation:
self.connectedlists = $(self.options.connectwith) .not(self.list) .droppable({ hoverclass: 'ui-selectablelist-active', drop: function(e, ui) { var sender = $(ui.draggable).closest('ul'), deferred = self.options.update.call(self, e, { sender: sender, receiver: $(this), items: selecteditems }); deferred.then(function () { self.removeselecteditems(); }); } });
and code plugin implementer looks this:
update: function (e, ui) { var self = this; homecoming $.post(url, { // info }) .done(function (data) { console.log('updated!'); }); }
i'm returning ajax phone call promise drop callback. within drop callback, want perform cleanup operation removeselecteditems always, utilize .then() function. doesn't seem running.
does pattern sound idea. can help me design? why isn't done function running within drop callback?
instead of using .then
, utilize .always
.
.then
used adding callbacks deferred object:
deferred.then(donecallbacks,failcallbacks)
try:
self.connectedlists = $(self.options.connectwith) .not(self.list) .droppable({ hoverclass: 'ui-selectablelist-active', drop: function(e, ui) { var sender = $(ui.draggable).closest('ul'), deferred = self.options.update.call(self, e, { sender: sender, receiver: $(this), items: selecteditems }); deferred.always(function () { self.removeselecteditems(); }); } });
update:
since developer specifying update function, there's possibility of developer not returning deferred object you. should check , throw exceiption in case.
self.connectedlists = $(self.options.connectwith) .not(self.list) .droppable({ hoverclass: 'ui-selectablelist-active', drop: function(e, ui) { var sender = $(ui.draggable).closest('ul'), deferred = self.options.update.call(self, e, { sender: sender, receiver: $(this), items: selecteditems }); if (deferred.always) { deferred.always(function () { self.removeselecteditems(); }); } else { $.error("update must homecoming deferred object."); } } });
jquery jquery-deferred
Comments
Post a Comment