destroy jQuery plugin instance - javascript

I've got a jQuery plugin that starts a setInterval when initialized on an element; something like this:
(function($){
$.fn.myPlugin = function(options){
/* snip */
var interval = setInterval(recurringFunction, options.interval);
/* snip */
};
})(jQuery);
I'd like to be able to do the general equivalent of jQuery UI's .destroy() function, where my plugin would clean up after itself and restore its target element (without removing it) to its original state (in my case, stopping that timeout). However, plain jQuery doesn't seem to have any standard convention for defining something like this. I don't use, need, or want jQuery UI. Is there a convention for cleaning up after a jQuery plugin, or do I just need to roll my own?
To clarify: I'm looking for a generic, common convention to define logic that cleans up after a plugin; I'm not asking how to clear a timeout.

You need to roll your own destroy method unless you are using the jQueryUI widget factory.

Related

Detect "hooked" DOM elements

So I have a set of jQuery plugins, really basic stuff, but I split the code into plugins because I don't like having a huge jQuery(document).ready() function where I store the entire application logic.
Each plugin has a "destructor", which is basically a function that I defined in the plugin prototype object. This function unbinds events used by the plugin, removes DOM elements that were added by the plugin etc.
Plugins are initialized like this:
$('.element').plugin();
Is there any way I can get all the elements that have my plugins attached to them, from another plugin which is supposed to replace the body HTML, so I can call the destructor function?
I was thinking to store each plugin instance inside a global array, then I can access that array from any plugin. But maybe there is a better way that doesn't use the global state?
I don't think there is a ready made method for it... but as a hack you can add a class to the target elements in your plugin and then use that class to get all elements with the widget initialized lke
$.fn.plugin = function(){
this.addClass('my-plugin-class');
}
then to initialize
$(element).plugin()
to get all elements with the plugin
$('.my-plugin-class')....
But if it is a jQuery UI widget then you can use the selector $(':ui-widgetname'), see this answer
Arun P Johny wrote the rigth idea -- just delete 'footprint' of your job by marking the affected DOM elements with some specific class name.
I want just add an idea. Plugins are the methods of the library and nothing more. If you need the destroyer for constructor -- just make another plugin for it:
$.fn.overture = function (){...};// construct
$.fn.crescendo = function (){...};// more construct
$.fn.quietFarewell = function (){...};// destructor for everything above
$(...).overture().crescendo().quietFarewell();

Use Zepto method on jQuery collection

I am using both jQuery and Zepto.
I want to conditionally invoke Zepto methods on a jQuery collection. Anyone have an eloquent solution? My code currently looks something like this:
// Obtain jQuery Object
var $selector = jQuery('.selector');
// Desktop
$selector.click( ... );
// Mobile
if (window.Zepto){
$selector.slideLeft( ... );
}
It is very brittle, but you can use Function.call to apply Zepto functions to jQuery objects. I did a proof-of-concept fiddle (http://jsfiddle.net/STnUQ/1/) and obviously it works for the simple css function.
var div = jQuery('.test');
Zepto().css.call(div, 'color', 'red');
So long as the underlying data structure of the jQuery object matches Zepto, it will work just fine. But this is not guaranteed (or even probable) and you should do extensive testing with your specific use.

Find elements which have jquery widgets initialized upon them

I am using the jQuery-File-Upload widget (although I believe this question can generalize to any jQuery widget). The API instructs the user to initialize the the widget using the fileupload method, thus:
$('#fileupload').fileupload();
My question is: Without knowing IDs, how can I find #fileupload (and any other elements which have had .fileupload() called upon them?
jQuery File Upload uses the jQuery UI widget factory under the hood, and that factory is known to register the widgets instances with the elements they extend using data().
Therefore, you can use filter() and write something like:
// Restrict ancestor if you can, $("*") is expensive.
var uploadified = $("#yourAncestor *").filter(function() {
return $(this).data("fileupload");
});
Update: From jQuery UI 1.9 onwards, the data() key becomes the widget's fully qualified name, with dots replaced by dashes. Therefore, the code above becomes:
var uploadified = $("#yourAncestor *").filter(function() {
return $(this).data("blueimp-fileupload");
});
Using the unqualified name is still supported in 1.9 but is deprecated, and support will be dropped in 1.10.

Wrapping a DOM element inside a JavaScript object

I've noticed a common pattern in the JavaScript I've been writing and was wondering if there is already a pattern out there that defines something similar as best practice? Essentially, it's how to get a DOM element and wrap it inside / associate it with a JavaScript object. Take this example, where you need a filter in your web app. Your page looks like this:
<html>
<head></head>
<body>
<div id="filter"></div>
</body>
</html>
You'd then wrap the element like so:
var myFilter = new Filter({
elem: document.getElementById('filter'),
prop: 'stacks-test',
someCallback: function() {
// specify a callback
}
});
And the JavaScript (where spec is an object passed to the constructor):
var Filter = function(spec) {
this.elem = spec.elem;
this.prop = spec.prop;
this.callback = spec.someCallback;
this.bindEvents();
};
Filter.prototype.bindEvents = function() {
var self = this;
$(this.elem).click(function(e) {
self.updateFeed();
};
};
Filter.prototype.updateFeed = function() {
this.prop; // 'stacks-test'
this.callback();
// ...
// code to interact with other JavaScript objects
// who in turn, update the document
};
What is this kind of approach called, and what are the best practices and caveats?
You might be interested in Dojo's widget library, Dijit - if I'm understanding your question correctly, it essentially does what you're asking, and a whole lot more.
In Dijit, a widget essentially encapsulates a DOM node, its contents, any JavaScript that defines its behavior, and (imported separately) CSS to style its appearance.
Widgets have their own lifecycle, registry, and events (including many which simply map to DOM events on a node within the widget, e.g. myWidget.onClick could effectively call myWidget.domNode.onclick).
Widgets can (but don't have to) have their initial contents defined in a separate HTML template file, through which it's also possible to bind events on nodes within the template to widget methods, as well as set properties on the widget that reference particular nodes in the template.
I'm barely scratching the surface here. If you want to read more on this, you can start with these reference pages:
http://dojotoolkit.org/reference-guide/dijit/info.html
http://dojotoolkit.org/reference-guide/dijit/_Widget.html (the base that all widgets extend)
http://dojotoolkit.org/reference-guide/dijit/_Templated.html (RE the HTML templating)
http://dojotoolkit.org/reference-guide/quickstart/writingWidgets.html (useful information when starting to write your own widgets)
http://dojotoolkit.org/reference-guide/dijit/ (for a bunch more info)
All said, I don't know what you're ultimately aiming for, and maybe this is all a bit much for your purposes (considering I'm throwing an entire other library at you), but figured it might pique your interest at least.
Continuing from my comment on the question, jQuery is a potential tool for the job, as it already provides some of the foundations for what you're after. However, having said that, it does introduce complexities of its own, and further, not all "jQuery ways" are equal. I'll suggest one way of using jQuery as your "object model", but it may or may not suit your needs.
First things first. The philosophy of jQuery is that you start everything by selecting the element first, using $(), or equivalently jQuery(). All operations conceptually begin with this. This is a slightly different way of thinking compared to creating an object that wraps an element and keeping a reference to that wrapper, but essentially this is what jQuery does for you. A call to $('#some-id') grabs the element with id of "some-id" and wraps it in a jQuery object.
One way: Write "Filter" plugins.
Replace your constructor with a initFilter() jQuery method. You can do this by modifying the jQuery prototype and using the jQuery object as your wrapper. jQuery's prototype is referenced by jQuery.fn, so:
jQuery.fn.initFilter = function (prop, callback) {
// Save prop and callback
this.data('filter-prop', prop);
this.data('filter-callback', callback);
// Bind events (makes sense to do this during init)
this.click(function () {
$(this).updateFeed();
});
};
Then do a similar thing for updateFeed():
jQuery.fn.updateFeed = function () {
this.data('filter-prop');
this.data('filter-callback')();
});
And use it like this:
$('#filter').initFilter(prop, callback);
Note that updateFeed can simply be in-lined into the click handler to prevent unnecessary pollution of the jQuery namespace. However, one advantage of using jQuery like this is that you do not need to keep a reference to the object if you need to invoke some function on it later, since jQuery ties all references to actual elements. If you'd like to call updateFeed programmatically, then:
$('#filter').updateFeed();
will then be invoked on the correct object.
Some things to consider
There are certainly downsides to this method. One is that all properties, which we've saved against the element using .data(), are shared between all jQuery functions that act on that element. I've attempted to alleviate this by prefixing the property names with "filter-", but depending on the complexity of your object(s), this may not be suitable.
Further, this exact method may not be so suitable for objects that require a lot of manipulation (i.e. objects with many functions) since all of these functions become common to all jQuery objects. There are ways to encapsulate all this which I won't go into here, but jQuery-ui does this with their widgets, and I'm experimenting with yet another alternative in a library I'm creating.
However, pulling back a bit, the only reason I suggested using jQuery in the first place is that your Filter object appears to be heavily tied to the DOM. It binds events to the DOM, it modifies the DOM based on user interaction, basically it appears to live in the DOM, so use something DOM-based, i.e. jQuery.

how to reuse effect instance on jquery

On mootools I'm used to declare once and reuse often. An FX example would go like this:
myEffect1 = new Fx.Slide($('myElement1'));
How should I go on jQuery? Meaning, the docs make it straightfoward to use:
$('myElement1').click(function(e){
this.slideToggle();
});
But if I want to call this effect somewhere else on my code will I have to re-declare it? And isn't this approach more resource hungry than the one above? How would this be properly done on jQuery?
Just manually cache the result set in a variable before calling the function, then reuse the function as needed:
var $el_one = $("#path .to > .selection"), // Stores jQuery object
$el_two = $("#path .to > .second"); // Stores jQuery object
var effect = function(){
$el_one.fadeIn();
$el_two.fadeOut();
}
Now you can call effect any time without reselecting the items. They instead use the cached jQuery selection to animate correctly.
If you need more clarity, let me know.
var slideToggleEffect = function(e){
this.slideToggle();
};
$('myElement1').click(slideToggleEffect);
$('myElement2').click(slideToggleEffect);
...
I'd go with a plugin in this case. For example here's a plugin that I use often - a very simple slide and fade toggle effect.
$.fn.slideFadeToggle = function(easing, callback) {
return this.animate({opacity: 'toggle', height: 'toggle'}, "fast", easing, callback);
};
Now you can call slideFadeToggle on any selector like this:
$("#somedom").slideFadeToggle();
Since every command acts on a jQuery object (the object returned by calling $() on a selector), the example you've given is the nearest comparison to what you're used to in MooTools, as far as I can see.
Is it more resource hungry? Well, that's a complex question to answer as instantiating objects is only one piece of client side code. Some framework methods for performing certain operations are better in some situations and worse in others.

Categories