Attach multiple jQuery plugins onto a single element - javascript

According to the jQuery plugin development guides from the Internet, the common practice of developing a jQuery plugin would be:
(function($) {
$.fn.myplugin = function(options){
//...
//Plugin common characteristic
//e.g. default settings
//...
//Attach to each desired DOM element
return this.each(function(){
//Instantiation stuff...
});
}
})(jQuery);
$(document).ready(function(){
$(".someclass").myplugin();
})
It seems to me that, if the elements with class "someclass" have been attached to another plugin, once those elements are going to attach to "myplugin", they will lose the original relationship to the previously attached plugin. I'm not sure if my thinking is completely correct. Please advise if any mis-understood.
Thank you!
William Choi

An element isn't "attached" to a plug-in. A plug-in just adds further methods to the jQuery wrapper for a matched set of elements. So just as the jQuery wrapper has parent and find, it also has the plug-in's myplugin method. These can all coexist as long as there are no naming conflicts.
It's true that if two different plug-ins both try to change something about the elements that cannot be two things at once (a plug-in that changes the foreground color to "blue" and another changing the foreground color to "red"), then they'd collide if you called both of the two plug-ins methods on the same element set. But that's just like two calls to css.
In particular, remember that there can be multiple event handlers assigned to the same event on the same element, so plug-ins that hook events need not necessarily conflict with one another (unless one of them stops the event during handling).
Here's an example of two plug-ins that act on the matched set of elements, but in non-conflicting ways:
plugin1.js:
(function($) {
$.fn.foo = function() {
this.css("background-color", "#b00");
return this;
};
})(jQuery);
plugin2.js:
(function($) {
$.fn.bar = function() {
this.css("color", "white");
return this;
};
})(jQuery);
Usage:
$("#target").foo();
$("#target").bar();
or even
$("#target").foo().bar();
Live example
Now, if both the foo and bar plug-ins tried to set the foreground color, the one called later would win.
Here's an example of a pair of plug-ins that both want to handle the click event, but do so in a cooperative way:
plugin1.js:
(function($) {
$.fn.foo = function() {
this.click(function() {
$("<p>Click received by foo</p>").appendTo(document.body);
});
return this;
};
})(jQuery);
plugin2.js:
(function($) {
$.fn.bar = function() {
this.click(function() {
$("<p>Click received by bar</p>").appendTo(document.body);
});
return this;
};
})(jQuery);
Usage:
jQuery(function($) {
$("#target").foo().bar();
});
Live example

There's no magical relationship going on. There's no central registry or snap-ins that "belong" to any one element or to any one plug-in.
Javascript objects are just hacked-up functions; when you "attach a plugin" to an element, you're just calling some third-party library function that does something to that element, and possibly stores some internal data to assist with its animation throughout the session.
So there is nothing legally stopping you from "attaching" multiple plug-ins to the same element, though of course whether they'll be logically compatible is quite another question.

Related

Observe a JS event, when you only know PART of the event name?

I've inherited some JS (that I can't change) that fires a bunch of events:
jQuery(document).trigger('section:' + section);
// where "section" changes dynamically
And I want to observe for ALL of these events, and parse out the value for section, and do something different depending on it's contents.
If it didn't change I could do this:
jQuery(document).on('section:top', doStuff );
But how do I observe an event if I only know the first part of that event name?
You cannot listen for all events in the style of $().on('section:*'), unfortunately. If you can change the code, I would do the following:
jQuery(document).trigger({
type: 'section',
section: section
});
Then you listen for it and don't need to parse anything out
jQuery(document).on('section', function(e){
if (e.section === 'top') {
// Something happened to the top section
}
});
If you want to minimize your code changes, leave the old event in there, that way existing code will be unaffected.
A different approach would be to use event namespaces.
jQuery(document).trigger('section.' + section);
jQuery(document).on('section', function(e){
if (e.namespace === 'top') {
// Something happened to the top section
}
});
I, however, prefer the first approach because event namespaces are most commonly used for a different purpose: to be able to remove events without being forced to keep a reference to the handler itself. See http://css-tricks.com/namespaced-events-jquery/ and http://ejohn.org/apps/workshop/adv-talk/#13. I prefer to use styles that other developers are used to, if they do the job.
I'm really not sure about your use case but you could overwrite $.fn.trigger method:
(function ($) {
var oldTrigger = $.fn.trigger;
$.fn.trigger = function () {
if (arguments[0].match(/^section:/)) {
doStuff(arguments[0].split(':')[1]);
}
return oldTrigger.apply(this, arguments);
};
})(jQuery);
var section = "top";
jQuery(document).trigger('section:' + section);
function doStuff(section) {
alert(section);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Here's what I ended up doing.
It's a combination of Juan Mendes's solution, and using a method from the prototype library
Originally, there was a function that ran this code:
myObject.adjustSection(section) {
jQuery(document).trigger('section:' + section);
}
// I couldn't edit this function
So I extended the function with prototype's wrap method, since my project used prototype as well as jQuery.
// My custom function wrapper
// extend adjustSection to include new event trigger
myObject.prototype.adjustSection = myObject.prototype.adjustSection.wrap(
function(parentFunction, section) {
// call original function
parentFunction(section);
// fire event w/section info
jQuery(document).trigger({
type: 'adjustSection',
section: section
});
}
);
Then, it runs the original one, but also fires my custom event that includes the section info.
Now, I can do this to observe that event and get the section type:
jQuery(document).on('adjustSection', function(event) {
event.section; // contains the section I need
});
Of course, this means I have to utilize both prototype and jquery within the same scope, which isn't the best thing in the world. But it worked.

Pattern for widgets in unobstructive javascript

I'm using JS and jQuery for the first time after a lot of experience with Java and C++. I'm loving jQuery's idea of $(document).on('click', 'btn-selector', react), but for more complex widgets I'm finding myself in the same rut over and over: in each react handler, I have to look up the widget as a whole and reconstruct all my knowledge about it.
For example, I'm making a simple widget out of <input>s with which the user can make a grading scale: 90 maps to an A, 80 maps to a B, etc. When one of the inputs changes, I want to check to make sure that the inputs are still in order (your scale can't go 90, 70, 80, for example).
So, I have something like
Actual
$(document).on('click', '.scale-input', function() {
var widget = $(this).closest('.scale-widget-container');
ensureLevelsAreInOrder(widget);
});
Almost every single handler has to have this first line to find its context. I'd much rather have code that looks like this:
Preferred
$(document).on('click', '.scale-input', ensureLevelsAreInOrder);
The problem is that in this form, ensureLevelsAreInOrder only has a reference to the input that changed, not the larger context.
In Java or C++, I would have called a constructor on the widget, and each input would have a handler with the context baked in via member variables. I could do something similar with
$(function() {
$('.scale-widget-container').scaleWidget();
});
with scaleWidget() setting up the contextualized handlers, but the page I'm working with loads a lot of its html with ajax and I don't have a reliable time to run that initialization.
Is this a common problem that we just have to deal with if we don't want JS in our HTML, or is there a solution I haven't come across yet?
Not sure what it is you're after exactly, but you don't seem to touch on two quite important concepts when it comes to JS: the event object, and closures. Both of these are open to you to get what you need:
event object:
The callback function is passed an argument, that describes the event itself, and references the elements affected by that event, This isn't exclusive to jQ (just google addEventListener), but it's quite handy:
$(document).on('click', '.scale-input', function(e)//<-- e is our event
{
console.log(e);//check console
});
Which, in vanilla JS would look like this:
document.addEventListener('click', function(e)
{
if (!e.className.test(/\bscale\-input\b/))
{
return e;
}
console.log(e);
}, false);
Another thing you might want to consider is enclosing references to whatever it is you need in an IIFE's scope:
(function()
{
var containers = $('.scale-widget-container'),
localBool = false,
asMany = 'varsAs you need',
previousScales = [],
inputs = $('.scale-input');//references to all DOM nodes you mention
$(document).on('click','.scale-input',function(e)
{
console.log($(this));
console.log(containers);
previousScales.push(this.value);//or something
console.log(previousScales);
//and so on.
});
}());
Hope this helped
Update:
If IE isn't a browser you don't care about that much, you could use one of the DOM-modified events, specifically DOMTreeModified:
(function()
{
var nodes = [];//<-- store current nodes here, if applicable
nodes.containsNode = function(node)
{
var i;
for (i=0;i<this.length;i++)
{
if (this[i] && this[i] === node)
{//node is set, return its index
return i;
}
}
//node not found, return -1
return -1;
};
document.body.addEventListener('DOMSubtreeModified',function(e)
{
var all = document.getElementsByClassName('scale-input'),
i;
for (i=0;i<all.length;i++)
{
if (nodes.containsNode(all[i]) === -1)
{
nodes.push(all[i]);//add new
}
}
},false);
}());
More on the mutation events, and their issues, on the DOM events wiki

Trigger code when custom event is being bound in jQuery

JQuery has great support for custom events - .bind("foo", function(e).... However what if the mechanic of triggering the event is not ready yet and has to be constructed only on those elements that have the event bound on?
For example I want a scrollin event that gets fired when an element is scrolled into a viewport. To do this, I would onscroll have to check all the elements and trigger scrollin on those that were outside the viewport and now are inside. This is not acceptable.
There are some tricks to speed it up. For example one of the plugins for this checks all the elements in "private" $.cache and does the checking only on those that have scrollin event bound.
But that's also ugly. What I need is an additional callback for the binding of the event (additional to the callback for handling) that would take care of the scroll management, that is to put the element(s) into some elementsCheckOnScrol cache array.
I'm looking for something like:
$.delegateBind("scrollin", function(jqSelection) { ... });
element.bind("scrollin", function(e) {..}); //Calls ^ after internal bind management
Edit: This would be nice api!
$.bind("bind", function(onWhat) { ... })
:-)
If I'm not misunderstanding you, you could patch the bind method like this:
(function($) {
var oldBind = $.fn.bind;
$.fn.bind = function(name) {
if(name === "scrollin") {
delegateFunction(this);
}
oldBind.apply(this, arguments);
};
})(jQuery);
What it does is checking whether a scrollin is being bound, and if so, calls your delegate function. After that it simply calls the original bind function which does all jQuery things like it does regularly.
After having added this code, you could use it like this: http://jsfiddle.net/pimvdb/g4k2G/.
function delegateFunction(selection) {
alert(selection.length);
}
$('a').bind('scrollin', function() {});
Note that this does not support object literals being passed to .bind (only (name, func)), but you could implement that as well.
I found an $.event.special API, but I don't know "how much" public it is. It is not in the docs and has been changed at least once before. http://benalman.com/news/2010/03/jquery-special-events/

Creating a jQuery plugin to cause individual elements to react when the window is resized. How do I handle the listeners?

I'm working on a plugin that causes something to happen in selected elements when the window is resized. The logic on what happens is perfectly fine, but I'm running into a conundrum when it comes to where to hook on the event listeners.
Basically, the code looks something like this:
$.fn.beAwesome = function() {
return this.each(function(){
// ???
});
}
While I've completed the rest of the plugin (and have it working just fine on, say, a click even on this), I can't put it "all together" without solving this central issue.
I considered just adding an extra bind resize to $(window) for each awesome element, but there'd be no way to access the element from within the closure:
$.fn.beAwesome = function() {
$window = $(window);
return this.each(function(){
$window.resize(function(){
// can't access initial awesome element
});
});
}
The other solution that sprung to mind was to instantiate a global data store (probably in $(document).data('beAwesome') or something like that. This, however, doesn't seem Javascript-like, blocking off access once the function runs its course, so I'd have to come up with some roundabout ways to do things like removing the hook. I've definitely seen approaches like these in Javascript libraries I've used in the past, but I don't know whether that's due to necessity or laziness on the authors' parts.
So is there an effective way to accomplish what I'm looking for?
You shouldn't bind to the resize event multiple times, will just end up with bloat and slowness.
What you could do is create a var to store all the elements that are to beAwesome. Bind to the resize event once. And then on resize do something will all the elements that are in the var.
(function($){ // closure to keep your pluggin contained.
var elems = $([]);
$(window).bind('resize.beAwesome', function(){
if (!elems.length) return; //no need to continue if elems in empty.
// Do something with elems here.
});
$.fn.beAwesome = function() {
elems = elems.add(this);
return this;
}
})(jQuery);
You also might want to namespace your resize event.

Only register a function with an event once?

I have a jQuery plugin that needs to register a click event handler:
$.fn.myPlugin = function (options) {
var settings = {
// snipped
};
$.extend(settings, options || {});
$("body").click(function () {
// Do Something
});
// Rest of the plugin
});
The problem is that multiple invocations register the function more than once. Since the function needs to stay attached, I can't use .one().
Is there a way if a function is already attached? Can I give it a name or so? Or do I have to set some boolean flag using closure magic?
Namespace your events.
$('body').unbind('click.myPlugin').bind('click.myPlugin', function() {
..code...
});
More on Namespaced Events.
A very easy method with good performance would be to set a data element on the body element:
if (!$.data(document.body, 'myPluginRegistered') {
$.data(document.body, 'myPluginRegistered', true);
// do your plugin code here
}
Easiest might be the boolean plus closure magic you suggested. Alternatively, you could get the list of all functions bound to "click" object, and see if the function you're attaching is there already.
This question shows how to get the list.
List all javascript events wired up on a page using jquery
Though, the namespace suggestion that came in after I first responded is probably simpler.

Categories