Creating custom jQuery function without selector prerequisite - javascript

I know that I can create custom jQuery plugins by using the $.fn.myFunction constructor, and the calling the custom function in JavaScript as $('selector').myFunction().
However, for a project I'm currently working on, I need to be able to define a function that does not require a selector to work.This is actually for a MessageBox plugin, which will act in a similar manner to C#'s MessageBox class. As such, I would ideally like to create the function as MessageBox, and then call it as follows:
var myMessage = $.MessageBox(); and then in turn myMessage.Show();
Notice the lack of selector brakets in the jQuery reference at the beginning of the function call.
Any advice on the best practice for this would be gratefully received.

This should work:
jQuery.MessageBox = function() {
var show = function() {
// something...
}
var hide = function() {
// something...
}
return {
show: show,
hide: hide
}
}

relipse has a good point - as you are cluttering the main namespace. A solution if you have more objects than just eg. MessageBox is to create your own namespace like this:
jQuery.myLib = {
MessageBox: function() {
var show = function() {
// something...
}
var hide = function() {
// something...
}
return {
show: show,
hide: hide
}
}
}
That means you are only taking one place in the main namespace (the name of your library, in this case myLib). You'd call it like this:
jQuery.myLib.MessageBox.show()

(function ($) {
$.MessageBox = function () {
var show = function () {
// something...
}
var hide = function () {
// something...
}
return {
show: show,
hide: hide
}
}
})(Jquery);
I think you better scope to Immediate invocation function to avoid collision with namespaces.

Related

jQuery global/local event execution order

I have a panel widget with a button. Clicking the button should execute some global actions related to all such widgets and after that execute some local actions related to this widget instance only. Global actions are binded in a separate javascript file by CSS class like this:
var App = function ()
{
var handleWidgetButton = function ()
{
$('.widgetBtn').on('click', function (e)
{
// do smth global
});
return {
init: function ()
{
handleWidgetButton();
}
};
}
}();
jQuery(document).ready(function()
{
App.init();
});
And in the html file local script is like this:
$("#widgetBtn1234").click(function (e)
{
// do smth local
});
Currently local script is executed first and global only after while I want it to be the opposite. I tried to wrap local one also with document.ready and have it run after global but that doesn't seem to change the execution order. Is there any decent way to arrange global and local jQuery bindings to the same element?
The problem you're having comes from using jQuery's .ready() function to initialize App, while you seem to have no such wrapper in your local code. Try the following instead:
var App = function ()
{
var handleWidgetButton = function ()
{
$('.widgetBtn').on('click', function (e)
{
// do smth global
});
return {
init: function ()
{
handleWidgetButton();
}
};
}
}();
$(function()
{
App.init();
});
Then in your local JS:
$(function() {
$("#widgetBtn1234").click(function (e)
{
// do smth local
});
});
Note that $(function(){}) can be used as shorthand for $(document).ready(function(){});. Also, make sure your JS file is located before your local JS, as javascript runs sequentially.
Alternatively, you can use setTimeout() to ensure everything's loaded properly:
(function executeOnReady() {
setTimeout(function() {
// Set App.isInitialized = true in your App.init() function
if (App.isInitialized) runLocalJs();
// App.init() hasn't been called yet, so re-run this function
else executeOnReady();
}, 500);
})();
function runLocalJs() {
$("#widgetBtn1234").click(function (e)
{
// do smth local
});
};
How about this instead:
var widget = $("#widgetBtn1234").get(0);//get the vanilla dom element
var globalHandler = widget.onclick; //save old click handler
// clobber the old handler with a new handler, that calls the old handler when it's done
widget.onclick = function(e){
//do smth global by calling stored handler
globalHandler(e);
//afterward do smth local
};
There might be a more jqueryish way to write this, but I hope the concept works for you.
-------VVVV----keeping old answer for posterity----VVVV--------
Why not something like this?
var App = function ()
{
var handleWidgetButton = function ()
{
$('.widgetBtn').on('click', function (e)
{
// do smth global
if(this.id === 'widgetBtn1234'){
//do specific things for this one
}
});
return {
init: function ()
{
handleWidgetButton();
}
};
}
}();
Please excuse any syntax errors I might have made as I haven't actually tested this code.
Check out my simple JQ extension I created on jsbin.
http://jsbin.com/telofesevo/edit?js,console,output
It allows to call consequentially all defined personal click handlers after a global one, handle missed handlers case if necessary and easily reset all personal handlers.

Getting value from this JQuery plugin

I've been experimenting with writing JQuery plugins lately, and I'm sure this is a very simple question. But, I seem to not be able to get a value inside of my plugin.
For example, I have the following code:
plugin.js
$(function($) {
$.fn.myPlugin = function() {
// alert the id from main.js
}
});
main.js
$(document).ready(function() {
$('#someDIV').attr('id').myPlugin();
});
You cannot define plugin on string. Use selector to call the plugin.
Have a look at this.
Use it like this:
(function ($) {
$.fn.myPlugin = function () {
this.each(function () {
// Allow multiple element selectors
alert(this.attr('id'));
});
return this; // Allow Chaining
}
} (jQuery));
$('.myClass').myPlugin();
DEMO
Tutorial
Try this:
(function($) {
$.fn.myPlugin = function() {
alert($(this).attr('id'));
}
}(jQuery));
See here: http://jsfiddle.net/1cgub37y/1/
You should pass only the object into your jQuery-extension function (not the object's ID), as below or in this fiddle (will alert "someDIV" onload):
// jQuery extension
// The object passed into jQuery extension will occupy keyword "this"
$(function($) {
$.fn.myPlugin = function() {
// Get the ID (or some other attr) of the object.
var id = $(this).attr("id");
// Now do something with it :)
alert(id);
}
});
$(document).ready(function() {
$('#someDIV').myPlugin();
});

Calling jQuery plugin public function within plugin

I know, there are quite a few examples on the Web, but finding real one out of them all is tough for beginner. So I want to create jQuery plugin with public methods. Example code:
(function($) {
$.fn.peel = function(options) {
var defaults = {
};
var settings = $.extend({},defaults, options);
this.public = function() {
alert("public");
};
var private = function() {
alert("private");
}
return this.each(function() {
//this.public();
private();
});
};
})(jQuery);
As I found, this is the way to make public function, which could be called like this :
var peel = $('img').peel();
peel.public();
So far it works as expected - public() can be called. But what if i want to call that function within my plugin? I commented out in this.each() because it does not work. How can i achieve that?
One way to create publicly accessible methods within your plugins is to use the jQuery UI widget factory. This is the framework that jQuery UI uses for all of it's supported UI widgets. A quick example would look like this:
(function( $ ) {
$.widget( "something.mywidget", {
// Set up the widget
_create: function() {
},
publicFunction: function(){
//...
}
});
}( jQuery ) );
var $w = $('#someelement').mywidget();
$w.mywidget('publicFunction');

jQuery and object literal function not working together

i was trying to organize my jquery code so i created an object literal, but now the focusTextArea is not working and my textarea value is not updating.
Thanks for your help.
html
<textarea id="test"></textarea>​
javascript
(function($,window,document,undefined){
var TEX = {
inputField: $("textarea#test"),
/* Init all functions */
init: function()
{
this.focusTextArea();
},
/* Function update textarea */
focusTextArea: function()
{
this.inputField.text('test');
},
}
$(document).ready(function(){
TEX.init();
});
})(jQuery,window,document);​
jsfiddle
http://jsfiddle.net/vBvZ8/1/
First of all, you haven't included jQuery correctly in the fiddle. Also, I think you mean to place the code in the head of the document (because of the document.ready handler).
More importantly perhaps the selector $("textarea#test") is run before the document is ready and therefore won't actually find the element correctly. I would recommend assigning inputField in TEX.init:
(function($,window,document,undefined){
var TEX = {
/* Init all functions */
init: function()
{
this.inputField = $("#test");
this.focusTextArea();
},
/* Function update textarea */
focusTextArea: function()
{
this.inputField.text('test');
},
}
$(document).ready(function(){
TEX.init();
});
})(jQuery,window,document);​
Updated example: http://jsfiddle.net/xntA2/1/
As a side note, textarea#test should be changed to just #test. The textarea bit is superfluous since there should be only one element on the page with id=test.
Alternative syntax to avoid looking for an element before it exists is to return the element from a function:
(function($,window,document,undefined){
var TEX = {
/* function won't look for element until called*/
inputField:function(){
return $("textarea#test")
},
init: function()
{
this.focusTextArea();
},
focusTextArea: function()
{
this.inputField().text('test');
},
}
$(document).ready(function(){
TEX.init();
});
})(jQuery,window,document);
DEMO: http://jsfiddle.net/vBvZ8/5/
I realize this is a simplified example...but you are also very close to creating a jQuery plugin and that may also be of benefit. Following provides same functionality as example:
(function($, window, document, undefined) {
$.fn.focusTextArea = function() {
return this.each(function(){
$(this).text('test');
})
};
})(jQuery, window, document);
$(function() {
$('textarea').focusTextArea()
});
DEMO: http://jsfiddle.net/vBvZ8/8/

How do I assign a real function into a javascript object to use as a callback?

I've got a Javascript mess that looks something like:
Note: Not working code, just trying to illustrate my problem...
$(function() {
$(foo).Something( { //Something is a grid control
buttons: {
add: {
onClick: function() { //Build dialog box to add stuff to grid
$('<div></div>')
.html('...')
.dialog({
buttons: {
done: { //Finished button on dialog box
OnClick: function() {
$(this).dialog('close');
}
}
}
});
}
}
}
} );
});
I'd like to replace some of the function(){...}s with real functions, to clean things up a bit and to get rid of all that indenting. How do I assign a real function to one of the callbacks rather than an anonymous function?
function abc(){
return false;
}
var callback = {click : abc}
You can then use callback.click.call or callback.click.apply
Give the function name instead of function(){ ... }.
+1 because of the awesome indentation example.
You can define named functions as Joyce stated; you can also considerably clean up that deeply nested code by just declaring some variables (function or not) and spreading the code into multiple, non-nested statements.
The dialog creation would be my first candidate for that type of refactoring (and it demonstrates uses a named function):
function CreateDialog() { //Build dialog box to add stuff to grid
$('<div></div>')
.html('...')
.dialog({
buttons: {
done: { //Finished button on dialog box
OnClick: function() {
$(this).dialog('close');
}
}
}
$(function() {
$(foo).Something( { //Something is a grid control
buttons: {
add: {
onClick: CreateDialog
}
}
}
} );
});
I should also note that you can initialize most jQuery objects (looks like you are using jQueryUI) after they are created. For example, you don't have to configure the buttons all in one shot: http://jqueryui.com/demos/dialog/#option-buttons
OK then, here goes my answer:
Oops.. You did functionname() (note the extra ()s). :sigh: That's what you get for working on this at 3 AM.

Categories

Resources