I'm authoring a plugin, and the plugin needs to do something like aggregate a set of jQuery objects. How does one do this?
For example:
<p><a>...</a></p>
<p><a>...</a></p>
With
(function( $ )
{
$.fn.myfunc = function( settings )
{
};
})(jQuery);
Within the context of the plugin invoked with $('p').myfunc(), how would I return all the elements, for example? The elements I'm returning will not necessarily be contained or near the elements selected, as this is just an example.
jQuery also accepts an array, so you can build your own node stack and create a jQuery object out of it.
Example:
(function( $ )
{
$.fn.myfunc = function( settings )
{
var stack = [];
stack.concat(this.find('a').toArray());
stack.concat($('a.hot-links').toArray());
return $($.unique(stack));
};
})(jQuery);
Or simply:
return this.find('a'); // as return result of plugin
Also, look at .pushStack(), which lets you add elements to an already existing jQuery object.
Related
var gridOptions = {
columnDefs: [
{headerName: 'Connection', field: 'Applicationaccess',minWidth:350,filter:'text',filterParams:{
filterOptions:['equals','contains']
},cellClass: 'all_grid_cell conn_cell',cellRenderer:function(params){
var p=params.value;
var $wrapper_div = $("<div>",{"class":"w3-dropdown-hover"});
var $newlink=$("<a>",{"href":"javascript:void(0)","class":"link w3-white","text":p});
$newlink.appendTo($wrapper_div);
var $ediv = $("<div>",{"class":"w3-dropdown-content w3-bar-block w3-border"});
var x=['meet','meeeeet','meeeeeeeet'];
for(i=0;i<x.length;i++){
var $btn=abc(x[i]);
$btn.appendTo($ediv);
}
$ediv.appendTo($wrapper_div);
return $wrapper_div;
}}
function abc(x){
var $btn=$("<button>",{"class":" w3-bar-item w3-button","text":x});
return $btn;
}
The output in Connection looks like [Object][object]:
My target is to display a hoverable dropdown in each cell of the Connection Column.
Following the documentation I created my desired div element and returned it via the cellRenderer function
Please help
I'm not a JQuery guru... but it looks like one issue you are running into is that you are returning a JQuery object (which in this case seems to be an array) rather than an HTML element. Change return $wrapper_div; to return $wrapper_div[0]; and it should work.
Here is an example showing the difference of what gets returned:
console.log("HTML Element:\n", $("<div>",{"class":"w3-dropdown-hover"})[0])
console.log("JQuery Object:\n", $("<div>",{"class":"w3-dropdown-hover"}))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Yep return $wrapper_div[0], because it's a jQuery DOM object you are returning and not a normal DOM object.
jQuery Dom object and HTML DOM object are different read the jQuery documentation. You will understand why you can use it as an array and why you return the first element.
Secondly why are you using $ in your variable names? This is not PHP you need not use $.
In jQuery $ is a special keyword which is associated to a special $ function which deals with selectors and accessing jQuery DOM objects. The $ is an alias for the jQuery () overloaded function.
I try to move some common application specific actions to jQuery plug-in by:
$.fn.extpoint = function() {...}
But I don't want to declare several extension points:
$.fn.extpoint1 = function() {...}
$.fn.extpoint2 = function() {...}
...
Instead I would like to use syntax sugar like:
$("#id").extpoint.func1().extpoint.func2()
With definition:
$.fn.extpoint = {}
$.fn.extpoint.func1 = function() {
this.val();
this.data("ip");
...
return this;
}
and call:
$("#id").extpoint.func1(...)
this point to $.fn.extpoint (dictionary with func1, func2, ... elements) instead of original jQuery object, when func1 evaluated.
Is it possible to make jQuery plug-in extendible?
PS. It is possible to pass function name as first argument to $.fn.extpoint and implement $.fn.extpoint('extend', func) call to extend (save to internal dictionary association between names and implementations) extension point. In that case use-cases look like:
$("#id").extpoint('func1', ...).extpoint('func2', ...)
but I look for way to make in more syntactic sugar...
The task I ask is hard to implement.
Official docs say:
Under no circumstance should a single plugin ever claim more than one namespace in the jQuery.fn object:
(function( $ ){
$.fn.tooltip = function( options ) {
// THIS
};
$.fn.tooltipShow = function( ) {
// IS
};
$.fn.tooltipHide = function( ) {
// BAD
};
})( jQuery );
This is a discouraged because it clutters up the $.fn namespace. To remedy this, you should collect all of your plugin's methods in an object literal and call them by passing the string name of the method to the plugin.
Another approach is maintain link to this as in http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js
So your calls looks like:
$.fn.addPlugin('test2', {
__construct : function(alertText) { alert(alertText); },
alertAttr : function(attr) { alert($(this).attr(attr)); return this; },
alertText : function() { alert($(this).text()); return this; }
});
$('#test2').bind('click', function() {
var btn = $(this);
btn.test2('constructing...').alertAttr('id').alertText().jQuery.text('clicked!');
setTimeout(function() {
btn.text('test2');
}, 1000);
});
Some related links:
http://milan.adamovsky.com/2010/02/how-to-write-advanced-jquery-plugins.html
http://milan.adamovsky.com/2010/09/jquery-plugin-pattern-20.html
http://ludw.se/blog/articles/19/patching-milans-jquery-plugin-pattern-for-jquery-16
http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js
Old style plug-in extention:
http://docs.jquery.com/Plugins/Authoring
jQuery Plugin Authoring and Namespacing
http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
http://mahtonu.wordpress.com/2010/09/20/jquery-plugin-authoring-step-by-step/
http://www.capricasoftware.co.uk/corp/template.php
Here is an overview of creating a plugin. I believe what you are asking about is called "chaining". It is what makes jQuery so easy to use, and it's good that you want to make sure that you are implementing it correctly.
The key thing to remember while developing your plugin in regards to chaining is to always return this; from your methods. That is what will allow you to keep the chain going.
I am ciruious to know what are the reasons that could cause a function "not being" one.
For example, I have the following:
$.fn.myfunction = function(options){
alert("test");
};
$("#hello").myfunction();
alert($.fn.myfunction instanceof Function);
Why would FireBug, log that it is not a function?
Thanks in advance.
Edit:
I would like a list of all the possibilities that could be the reason for the error.
This isn't an error I got, but I just want to widen my perspective and be aware of more possibilities.
Setting $.fn.myfunction makes the myfunction function available to the object returned by $(selector), not to $ itself.
Thus, $("#hello").myfunction is a function but $.myfunction is not. If you really want $.myfunction to be a function for some reason (e.g., it's a utility function that doesn't need a jQuery object list to operate), just set it explicitly, without using $.fn:
$.myfunction = function() { .... }
What is $ in the context? jQuery perhaps? If it´s jQuery you´re using, please tag your question as such.
(function( $ ) {
$.fn.myPlugin = function() {
return this.each(function() { // Maintaining chainability
var $this = $(this);
// Do your awesome plugin stuff here
console.log($this); // TEMP
});
};
})( jQuery );
Usage: $('#hello').myPlugin();
See more information about jQuery plugin authoring.
adding parentheses seemed to work:
alert($().myfunction instanceof Function);
returns true.
I'm am trying to create a jQuery plugin that will add new namespace functions to the context object(s), while maintaining full chain-ability. I'm not sure if it's possible, but here's an example of what I have so far:
(function ($) {
var loadScreen = $('<div />').text('sup lol');
$.fn.someplugin = function (args) {
var args = args || {},
$this = this;
$this.append(loadScreen);
return {
'caption' : function (text) {
loadScreen.text(text);
return $this;
}
};
}
})(jQuery);
This works fine if I do $(document.body).someplugin().caption('hey how\'s it going?').css('background-color', '#000');
However I also need the ability to do $(document.body).someplugin().css('background-color', '#000').caption('hey how\'s it going?');
Since .someplugin() returns it's own object, rather than a jQuery object, it does not work as expected. I also need to be able to later on access .caption() by $(document.body). So for example if a variable is not set for the initial $(document.body).someplugin(). This means that somehow how .caption() is going to be set through $.fn.caption = function () ... just for the document.body object. This is the part which I'm not quite sure is possible. If not, then I guess I'll have to settle for requiring that a variable to be set, to maintain plugin functions chain-ability.
Here's an example code of what I expect:
$(document.body).someplugin().css('background-color', '#000');
$('.non-initialized').caption(); // Error, jQuery doesn't know what caption is
$(document.body).caption('done loading...');
Here's what I'm willing to settle for if that is not possible, or just very inefficient:
var $body = $(document.body).someplugin().css('background-color', '#000');
$('.non-initialized').caption(); // Error, jQuery doesn't know what caption is
$body.caption('done loading...');
The be jquery-chainable, a jQuery method MUST return a jQuery object or an object that supports all jQuery methods. You simply have to decide whether you want your plugin to be chainable for other jQuery methods or whether you want it to return your own data. You can't have both. Pick one.
In your code examples, you could just define more than one plugin method, .someplugin() and .caption(). jQuery does not have a means of implementing a jQuery plugin method that applies to one specific DOM object only. But, there is no harm in making the method available on all jQuery objects and you can only use it for the ones that it makes sense for.
I think you could use this:
(function ($) {
var loadScreen = $('<div />').text('sup lol');
$.fn.someplugin = function (args) {
var args = args || {},
$this = this;
$this.append(loadScreen);
return(this);
}
$.fn.caption = function (text) {
loadScreen.text(text);
return this;
}
})(jQuery);
$(document.body).someplugin().css('background-color', '#000');
$('.non-initialized').caption('whatever');
$(document.body).caption('done loading...');
If there's supposed to be some connection between the two .caption() calls, please explain that further because I don't follow that from your question.
Is it inadvisable to add methods to a JQuery element?
eg:
var b = $("#uniqueID");
b.someMethod = function(){};
Update
Just to clarify, I am working on a JS-driven app that is binding JSON data to local JS objects that encapsulate the business logic for manipulating the actual underlying DOM elements. The objects currently store a reference to their associated HTML element/s. I was thinking that I could, in effect, merge a specific instance of a jquery element with it's logic by taking that reference add adding the methods required.
Well, there's nothing inherently wrong with it. It is, however, pretty pointless. For example:
$('body').someMethod = function(){};
console.log($('body').someMethod); // undefined
You are attaching the new function only to that selection, not to all selections of that element.
What you should do instead is to add a new function to jQuery.fn, which is a shortcut for jQuery.prototype:
jQuery.fn.someMethod = function() {
if (this[0].nodeName == 'body') {
// do your function
}
return this; // preserve chaining
};
The problem is that your function would be quite transient. A further requery and it will be gone. You can extend the jQuery object itself by $.fn.someMethod = function() {} and this method will be available for all queries.
$.fn.someMethod = function() {}
var b = $("body");
b.someMethod();
Or you can create a jQuery plugin. You can define a plugin this way:
$.fn.someMethod = function(options) {
# ...
});
Call it using $('body').someMethod();