How can I use an extended jQuery function? - javascript

I use a jQuery plugin called ColorPicker.
The source that I include is here.
So, my code is just $("#some_id").ColorPicker(some_options), as indicated in the doc and it works fine.
But now, I want to use only one function from the source, function HexToHSB(), but I do not know how to use it as I do not completely understand jQuery plugins import.
I tried $.ColorPicker.HexToHSB() but it did nothing.

You would not be able to do this as these functions are private to the module ColorPicker and you do not have access to them. This is how you can understand the plugin to be working:
// ColorPicker is an object with public methods, but no access to the private variables and functions in it.
// The function is being invoked at runtime, returning an object
var ColorPicker = function(){
var privateVariables;
var privateFunction = function(){...};
...
return {
publicFunction1 = function(){...},
publicFunction2 = function(){...},
}
}();
// jQuery is extended here
$.fn.extend({
ColorPicker: ColorPicker.publicFunction1,
ColorPicker: ColorPicker.publicFunction2,
});
There are two ways to fix your problem:
Copy the relevant functions out from that jQuery library and use them
Add code to the jQuery library to expose the private functions (e.g. add a custom function to line 375 that calls HexToHSB() and then extend jQuery with this function in line 478)

Related

How to make a jQuery plugin function callable for stand-alone use, that does not operate on a collection

I read the jquery documentation of plugin authoring and am familiar with that. However, the examples given always operate on a set of previously matched elements. I want to create a function that can do both:
// example usage of my to-be-created plugin function
// this is the way described in the docs, and I know how to do that
$("a").myFunction ()
// but I also want to be able to call the function without a collection:
$.myFunction ();
If $.myFunction ()is called without a collection to operate on, it would create it's own collection of what elements to match - kind of an initialization process (but not necessarily run only once). Also, $.myFunction ()should maintain chainability.
The pseudocode of what I want to achieve:
// [...]
function myFunction (): {
if (notCalledOnACollection) {
// this should run when called via $.myFunction ()
$elements = $("a.myClass");
}
else {
$elements = $(this);
}
return $elements.each (function () {
// do sth. here
});
}
I would really like to keep all of the functions implementation/functionality within a single function definition, and not have two separately named functions or two equally named functions in two separately places within the jQuery object.
And of course I could add a parameter myFunction (do_init) that indicates what branch of the if statement to execute, but that would clutter my argument list (I want to use that approach for multiple plugins, and there will be argumentes to myFunction () that I just left out here for simplicity).
Any good suggestions?
By simply adding another reference in the plugin definiton, you can easily use the standard plugin code:
(function( $ ) {
$.myPlugin = $.fn.myPlugin = function(myPluginArguments) {
if(this.jquery)
//"this" is a jquery collection, do jquery stuff with it
} else {
//"this" is not a jquery collection
}
};
$.fn.myPlugin.otherFunc = function() {
};
})( jQuery );
The only difference here is the $.myPlugin = part which allows you to directly call your plugin without running jquery's selector function. Should you decide you need other functions or properties, you can create them as properties of your plugin.
Usage:
//using a selector (arguments optional)
$(".someClass").myPlugin();
//using the options variable - or whatever your arguments are
$.myPlugin({id: "someId"});
//accessing your other functions/properties
$.myPlugin.otherFunc();

refer to the plugin object within the plugin

I am trying to access plugin through this, in order to refer to methods added later down in the chain.
$.fn.test = function(){
console.log(this);
}
but this refers to the elements I have used to call the plugin, and not the plugin itself.
How can I access the plugin, and thus any methods attached to it?
Use $(this) if you want the jQuery object.
You can also try this to add plugin to jQuery.
(function($){
$.extend($.fn, {
test: function(){
//Plugin code here
//here this will point to jQuery object
}
};
})(jQuery);

In JavaScript is it possible to add to a callback function instead of overwriting it?

I don't know if I'm saying this right, so I'll just ask by explaining with an example.
Let's say I've written a jQuery plugin with an onShowEdit callback.
I later use my plugin and add a bunch of other default functions/methods to the event:
$('.editable_module:not(.custom)').editable({
onShowEdit: function(el){
initRequired();
$(':radio, :checkbox', el).prettyCheckboxes();
initDatePickers();
initChosen();
initMaskedInputs();
$('.dynamic_box.tabs').dynamicBoxTabs();
$('.trigger_dynamic_box').triggerDynamicBox('true');
}
});
So now I have a basic/default element (.editable_module) that calls the plugin and has some methods/functions that are going to be used in all instances.
My question comes when I have a need to add something to this for a 'one time' kind of deal (I need to add some behavior to this callback/event but not something that is used normally). Is it possible to extend or add to this callback/event without overwriting it? I mean, I know I can go in and do this:
$('#new_selector').editable({
onShowEdit: function(el){
initRequired();
$(':radio, :checkbox', el).prettyCheckboxes();
initDatePickers();
initChosen();
initMaskedInputs();
$('.dynamic_box.tabs').dynamicBoxTabs();
$('.trigger_dynamic_box').triggerDynamicBox('true');
//ADD SOME NEW STUFF HERE
}
});
But is that really my only option?
Thanks in advance for any input/suggestions.
You could consider jQuery's own event system as follows: http://jsfiddle.net/VQqXM/1/. You can integrate this in your $.fn function pretty easily - just pass the appropriate function as property of the object instead of a function literal.
$("input").on("foo", function() {
alert(1);
});
// later
$("input").on("foo", function() {
alert(2);
});
// later
$("input").trigger("foo"); // alerts 1 and 2
You can simply use .on/.off to bind and unbind events, and trigger them all with .trigger. jQuery also supports namespacing of the event names to make sure you're not using an already used event.
You could use the new $.Callbacks() method
var $onShowEditCBObj = $.Callbacks();
function onShowEditHandler() {
$onShowEditCBObj.fire();
}
$('#new_selector').editable({
onShowEdit: onShowEditHandler
});
// add default event to callbacks obj
$onShowEditCBObj.add(function(){
initRequired();
$(':radio, :checkbox', el).prettyCheckboxes();
initDatePickers();
initChosen();
initMaskedInputs();
$('.dynamic_box.tabs').dynamicBoxTabs();
$('.trigger_dynamic_box').triggerDynamicBox('true');
});
// add a one time method to the callbacks obj
function oneTimeEvent () {
alert("worky");
$onShowEditCBObj.remove(oneTimeEvent);
}
$onShowEditCBObj.add(oneTimeEvent)
With this setup, you can change what callbacks will be fired without having to do anything extra to the editable plugin.
Edit: I didn't realize that you wrote the plugin. With that in mind, pimvdb's answer is more robust than requiring the developer to code a certain way.
If I understand the question correctly, the key word here is "factory".
jQuery is itself a factory but to get what you describe, you need your plugin also to be a factory within the factory. That requires the plugin to be written in a certain way.
Probably the easiest approach is to use jQuery's UI widget factory. Read about it here.
Defining a separate function for onShowEdit should work.
var myOnShowEdit = function(el, extra_fn) {
//standard functionality goes here
if (typeof extra_fn==='function') extra_fn(); //support for extra stuff
}
$('.editable_module:not(.custom)').editable({
onShowEdit: function(el) {
myOnShowEdit(el);
}
});
$('#new_selector').editable({
onShowEdit: function(el) {
myOnShowEdit(el, function(){console.log('hi');});
}
});
This will give you fair flexibility to add whatever functionality you need in addition to the standard stuff. Just be aware of how this may shift contexts.

javascript: anonymous function expose functions (how frameworks really works)

i was exploring in the last few days how big frameworks works , how they assign their function name and it can't(?) be override , i pretty much know how framework work with anonymous function , for example they do it this way or similar version :
(function(){
var Sizzle = function (){
var x;
};
Sizzle.f = function(){
alert("!");
};
window.Sizzle = Sizzle;
})();
i still don't get few things about those huge frameworks and i hope i can find answer :
how do they assign function name and the name can't be override?
in the code above to call the function i need to write Sizzle.f() to get the function to work , but when i use jquery i don't write Jquery.show() , just show() , how do they vanish the "jquery" from "jquery.show()" function call?
by saying the name can't be override i mean , if i create function with one of the jquery functions names , the jquery function will work.
thanks in advance.
As has been shown for #2, it's really easy for BIG_NAMESPACE.Functions.doStuff to be added to anything you want.
var _ = BIG_NAMESPACE.Functions.doStuff;
_(); // runs BIG_NAMESPACE.Functions.doStuff;
As for #1:
Most libraries DO let their functions be overwritten.
It's the values that are inside of the framework's closure which are preserved, for safety reasons.
So you could do something like:
BIG_NAMESPACE.Functions.doStuff = function StealEverything() {};
(BIG_NAMESPACE.Functions.doStuff === StealEverything) // true;
But doStuff would have NO access to any of the variables hidden inside of the framework's closure.
It would also mean that until the page was reloaded, doStuff would also not work the way you want it to.
HOWEVER, in newer versions of JavaScript (ECMA5-compatible browsers), it WILL be possible to do something like what you're suggesting.
BIG_NAMESPACE = (function () {
var do_stuff = function () { console.log("doin' stuff"); },
functions = {
set doStuff (overwrite) { }
get doStuff () { return do_stuff; }
};
return { Functions : functions };
}());
Then, this will work:
BIG_NAMESPACE.Functions.doStuff(); // "doin' stuff"
BIG_NAMESPACE.Functions.doStuff = function () { console.log("ain't doin' jack"); };
BIG_NAMESPACE.Functions.doStuff(); // "doin' stuff"
However, Frameworks aren't going to use this for a LONG time.
This is not even remotely backwards compatible. Maybe in 2016...
There were defineGetter and defineSetter methods as well, but they aren't a formal part of the JavaScript language. Like innerHTML, they're things that the browser vendors put in, to make life better... ...as such, there's no real guarantee that they're going to be in any/all browsers your users have. Plus, they're deprecated, now that new browsers use the get and set constructs that other languages have.
(function(){
var jqueree = {};
jqueree.someval = 22;
jqueree.somefunc = function(){ alert(this.someval); };
window.jqueree = jqueree;
window.somefunc = function(){ jqueree.somefunc.call(jqueree); };
window.$$$ = jqueree;
})();
// all equivalent
window.somefunc();
window.jqueree.somefunc();
$$$.somefunc();
somefunc();
Answering your Questions
At the top of jQuery you'll see: var jQuery = (function() {, which creates the local function (its incomplete; the }); occurs elsewhere).
At the very end of jQuery you'll notice the following, which is how it attaches it to the global namespace:
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
I have never seen a jQuery function called without referencing the jQuery object. I think you always need to use jQuery.show() or $.show(); however maybe you're saying you don't have to call window.jQuery.show(), which you are permitted to drop the window, since that is the default.
Using your example
(function(){
/* This is where Sizzle is defined locally, but not exposed globally */
var Sizzle = function (){
var x;
};
/* If you put "window.f = Sizzle.f = function(){" then you could *
* call f() w/o typing Sizzle.f() */
Sizzle.f = function(){
alert("!");
};
/* The following line is what makes it so you can use Sizzle elsewhere *
* on your page (it exposes it globally here) */
window.Sizzle = Sizzle;
})();
use function _name_() {} and the name is static
the simply use var $ = jQuery; to create an alias.
jQuery works this way:
Supposed you have this jQuery code:
$("#title").show();
You have three elements to that line.
$ is a javascript function
"#title" is an argument to that function
.show() is a method call
Here's how it works.
Javascript executes the function named $ and passed it an argument of "#title".
That function does it's business, finds the #title object in the DOM, creates a jQuery object, puts that DOM element into the array in the jQuery object and returns the jQuery object.
The Javascript execution engine then takes the return value from that function call (which is now a jQuery object) and looks for and executes the .show() method on that object.
The .show() method then looks at the array of DOM elements in the jQuery object and does the show operation for each DOM element.
In answer to your question, there is no .show() all by itself. It's a method on a jQuery object and, in this example, that jQuery object is returned from the $("#title") function call.

Is it possible to write a second non-static, selecting, priviledged function in a JQuery Plugin?

Almost all of the examples in the jQuery tutorials that I've read, usually use one major public function for their selecting plugin. When I say 'selecting' plugin, I mean one that is not simply a static function extended onto jQuery.
For example:
(function($) {
jQuery.fn.actionList = function(options) {
var opts = $.extend({}, $.fn.actionList.defaults, options);
return this.each(function(){
alert(this);
});
};
$.fn.actionList.defaults = {
listHtml: '<div>Set the list html</div>'
};
})(jQuery);
but not:
jQuery.log = function(message) {
if(window.console) {
console.debug(message);
} else {
alert(message);
}
};
This works fine for most things, but what I would like to do is be able to call a second function on the object returned from the first call.
var actionBox = $('actionBox').actionList(options);
//Many light-cycles later
actionBox.refreshData(data);
or maybe even:
$('actionBox').actionList(options);
// laaateerr
$('actionBox').actionList.refreshData(data);
I'm guessing one or both of these is not possible or, at least not advisable, but I'm only now getting into the deepest aspects of jQuery and javascript.
Could someone explain how to do this, or if it's not possible or advisable, why? and what they would do instead?
Thanks for reading!
I'm not quite sure what you're getting at, but you can call a second function on the object returned from the first function - in fact, it is very much encouraged to return a jQuery object from your plugins, and the reason why you can chain commands in jQuery.
Using your examples
var actionBox = $('actionBox').actionList(options);
//Many light-cycles later
actionBox.refreshData(data);
would work fine, so long as both .actionList() and .refreshData(data) commands both return a jQuery object.
And
$('actionBox').actionList.refreshData(data);
would need to be
$('actionBox').actionList().refreshData(data);
EDIT:
Looking at the jQuery source code,
jQuery.fn = jQuery.prototype = {
/*
Load of 'property' functions of jQuery object...
*/
}
so, adding properties (a.k.a plugins) to jQuery.fn extends the prototype of the jQuery object. When you call
$(selector, context);
a new jQuery object is returned, using the init property function of the jQuery object
jQuery = window.jQuery = window.$ = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
I think I've got a plugin that might be very useful for you. It allows you to apply any constructor/object to jQuery as it's own namespace AND you can use 'this' as you would normally with jQuery to refer to the object set. Using this[methodName] will call a method on your object, etc.
http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js
Some code samples are here:
http://groups.google.com/group/jquery-dev/browse_thread/thread/664cb89b43ccb92c/34f74665423f73c9?lnk=gst&q=structure+plugin+authoring#34f74665423f73c9
It's about halfway down the page.
I hope you find it useful!

Categories