Can i use a function name in my jquery plugin parameters? - javascript

I am creating a form validation plugin for jQuery and would like it to call a function once the form has been successfully validated.
The plugin will have a default callback function, but I would like to modify this through the options parameter.
Unfortunately what i have (below) does not work. Any ideas?
(function($){
$.fn.extend({
validify : function(options) {
var defaults = {
callback: "callbackFunc",
};
var options = $.extend(defaults,options);
return this.each(function(){
//validation code here
//if valid call the function
if(errors==0){
options.callback;
}
function callBackFunc(){
// the default callback function
}
...

Remove the quotes and you're golden.
This will pass a function reference. You can then call it by doing options.callback();
You will also need to declare the function before you pass the reference along. You could get around this by doing this instead:
callback: function() { callbackFunc(); }

Pass the function itself, rather than its name (ie, remove the quotes):
(function($){
function callBackFunc(){
// the default callback function
}
$.fn.extend({
validify : function(options) {
var defaults = {
callback: callbackFunc // IMPORTANT: remove quotes AND trailing comma
};
var options = $.extend(defaults,options);
return this.each(function(){
//validation code here
//if valid call the function
if(errors==0){
options.callback(); // note parentheses
}
...

Related

jQuery handler not defined (handler.guid)

i have a function for attaching handlers to events and it's working when a pass it an anonymous function but when i declare the function as a field in the object it doesn't work and the handler is undefined
validationObj = (function(API){
this.validate = function (id2, idN2){
//code
//doesn't work
//this way i get an handler.guid error on functionFromMyApi
API.attach_events( {"keyup": run_func(id1, id2) },"id");
// work's ok
API.attach_events( {"keyup": function(){
// same code here from run_func
}
},"id");
//code
};
var run_func = function (id1, id2){
var obj1 = document.getElementById(id1);
var obj2= document.getElementById(id2);
var show_err = false;
API.functionFromMyApi ();
//code
// more code
};
})(api);
i use jQuery 1.2.6
When you do:
API.attach_events( {"keyup": run_func(id1, id2) },"id");
you're not passing it a function reference, like you do when you use an anonymous function, you're instead calling run_func and passing its return value. If run_func had no parameters then you could do:
API.attach_events( {"keyup": run_func},"id");
However, since it does, you're still going to need to use an anonymous function:
API.attach_events( {"keyup": function() {run_func(id1, id2)} },"id");

How to get the right class context from a method when it is invoked from a callback

I'm using Class.js for creating classes.
I'm not getting the right context inside a method when invocked from a call back function
My code is
WordCloud = MyClass.extend({
init: function(data) {
var me = this;
(......).on("onComplete", this.draw);
},
show: function(word) {
alert(word)
},
draw : function(words){
console.debug(this); // prints element that triggred `onComplete` action
console.debug(words); // "Hi"
console.debug(me); // me is not defined
me.show(words) // Need to call this method
}
});
Problem is draw method is fired when an action is completed, but inside draw method this is not the actual class instance, but the element that triggred the callback action.
I can't pass exta arguments while calling this.draw as it is a call back function and onComplete has only one parameter.
How can I call the show method from draw?
If you do not have to support Internet Explorer 8 or lower, you can use bind():
init: function(data) {
var me = this;
(......).on("onComplete", this.draw.bind(this));
}
Otherwise, if you're already using jQuery, you can leverage $.proxy(), which works the same way:
init: function(data) {
var me = this;
(......).on("onComplete", $.proxy(this.draw, this));
}
I use a helper function for these cases.
function hitch(obj, func) {
return function() {
return obj[func].apply(obj, arguments || [])
};
}
To call it you would use hitch(this, 'draw'); instead of this.draw.
Or to make it even simpler you could add a simplified version to your base class
function hitch(func) {
var that = this;
return function() {
return that[func].apply(that, arguments || [])
};
}
And just call this.hitch('draw');.

jQuery function: pass callback functions as optional arguments to another function

I've written the following convenience function to let me easily put jquery UI autocomplete on elements.
jQuery.fn.bindAutocomplete = function() {
$(this).each( function() {
$(this).autocomplete({
source: $(this).data('autocomplete-source')
});
});
}
I always use the convention of attaching data-autocomplete-source to an element so I can call this anywhere just like so:
$('input#name').bindAutocomplete();
Now, the autocomplete function can take callback functions as optional arguments after the options hash. I almost never need to mess with that, but I've found that in a small number of instances I'd like to pass a success function through. Obviously I can just rewrite the full autocomplete function when I need to pass it callbacks, but I'd rather just rewrite my bindAutocomplete() function so it can accept optional callback functions and pass them through to autocomplete().
So, how do you do that?
Update
I tried this, based on a close but not quite answer below:
jQuery.fn.bindAutocomplete = function(callbacks) {
$(this).each( function(callbacks) {
options = $.extend({source: $(this).data('autocomplete-source')}, callbacks);
$(this).autocomplete(options);
});
}
This binds autocomplete correctly whether you pass callbacks in or not, but if you do pass callbacks they don't get called.
Ie: the following triggered autocomplete but not the callback.
$('input#name').bindAutocomplete({ select: function(){alert("working");} })
I guess you can do this if that's what you mean...
jQuery.fn.bindAutocomplete = function( opts ) {
return this.each(function(){
opts = $.extend({
source: $(this).data('autocomplete-source')
}, opts);
$(this).autocomplete( opts );
});
}
$('input#name').bindAutocomplete({
change: function() { ... },
close: function() { ... }
});

How to pass parameter in javascript function

I want to pass one parameter to a function called ForPaste().
My function is given below:
var regex = /^[A-Za-z0-9ĀĒĪŌŪāēīōū\.\-\~\`\'' ]*$/;
var SalaryRegex = /^[A-Za-z0-9\,\.\/\$ ]*$/;
$.fn.ForPaste = function () {
return this.each(function () {
$(this).bind('input propertychange', function () {
var value = $(this).val();
if (!regex.test(value)) {
$(this).val("");
}
});
});
};
This function is in a common JS file. It is called on individual pages. I want to test the regex depending on the parameter passed. So can I know the method about to call the ForPaste() function with the parameter.e.g $("#Text1").Forpaste('FromForm1'); and I get this FromForm1 in the ForPaste() function.
You define a formal parameter for your function.
// formal parameter--v
$.fn.ForPaste = function (the_value) {
alert( the_value ); // displays the argument passed
// rest of your code
};
Whatever value was passed to ForPaste() will be referenced by the_value. (Of course you can change the name to any valid identifier.)
not sure what you are trying to do, because the answer seems so obvious. Will this do?
$.fn.ForPaste = function (theName) {
if (theName.test(//)){
return this.each(function () {
....
});
}
return false
};
you can access the parameters by looking at arguments which isn't an array, but seems to be one. from within the function you can do an var theName=arguments[0] to get the value of the first parameter

jQuery binding function on focus

I'm writing a little plugin for jQuery and so far I've got this:
(function($){
$.fn.extend({
someFunction: function() {
return this.each(function() {
var obj = $(this);
obj.focus(someInternalFunction(obj));
});
}
});
function someInternalFunction(obj) {
};
})(jQuery);
The problem is, when i attach someFunction to the object, the object gets focus and binding of someInternalFunction on focus event fails.
Then I tried to bind function to wrap the function call in the other function:
obj.focus(function() {
someInternalFunction($(this));
});
This code works, but it isn't pretty at all. Is it possible to bind function on focus without wrapping it in the other function?
$.fn.bindFocus() = function(){
var internalFunction = function(){
var $this = $(this),
self = this;
// try do stuff here
};
return this.each(function(){
$(this).bind('focus', internalFunction);
});
}
$('#myElement').bindFocus();
Hope it'll help ?
EDT. Sorry, first time get you wrong :)
Here:
obj.focus(someInternalFunction(obj));
^^^^^
... you're calling the function, meaning that its return value is the thing that actually ends up being passed to focus(). Instead you want to pass a function to focus(). Given the fact that you want to pass obj to someInternalFunction, you'll have to define an additional function to wrap it all:
obj.focus(function(){
someInternalFunction(obj);
});
Just to make things clear:
var x = function() { return 3; }; // Defining a function
x; // -> this is a function reference
x(); // -> this is 3

Categories

Resources