Javascript Call Function with String - javascript

I'm sending callback strings from php to javascript.
var PostType = function () {
return {
create: function(form, response) {
Custom.resetForm(form);
$('#create-form').modal('hide');
Grid.reset();
}
};
}();
I have to call PostType.create method but it's not working.
I'm calling it like:
//Call function
callFunction: function(func, form, response) {
var fn = window[func];
if(typeof fn === 'function') {
fn(form, response);
} else {
console.log(typeof fn);
return false;
}
}
// Call
Custom.callFunction(response.callback, $form, response);
What should i do?

Okay, got it.
When calling object > method with window;
window["object"]["method"];
So i'v modified my callFunction to this:
callFunction: function(func, form, response) {
//Check for func string if contains any "." (dot)
if(func.indexOf('.') !== -1) {
// If so; split "." character to get Object name and the method name
func = func.split(".");
var fn = window[func[0]][func[1]];
} else {
var fn = window[func];
}
if(typeof fn === 'function') {
fn(form, response);
} else {
return false;
}
},

Related

return function from Javascript class object

I have modularized my Javascript code in this style:
var groupHandler = function( constructorOptions )
{
"use strict";
var init = function( optionsToSet )
{
jQuery.extend( options, optionsToSet);
return this;
};
var newGroup = function()
{
}
var call = {
init: init,
options: options,
newGroup: newGroup
};
if(typeof myPublicTestNamespace == "undefined"){//http://stackoverflow.com/a/9172377/123594
return {
init: init,
newGroup: newGroup
};
}else{
return call;
};
init( constructorOptions );
};
In one of my modules I have a list of functions from other modules to call like this:
validatorFunctions = call.getLocalStorageArray( 'validatorFunctions', model);
for (var f=0;f < validatorFunctions.length;f++){
if (callFunction = call.getFunction( validatorFunctions[f] )){
valid = callFunction( loopRowId, fields, call );
if (!valid) break;
}
}
I'd like to be able to call functions in other modules by using a "." syntax in my function call name:
var getFunction = function( functionName )
{
if (functionName.indexOf( '.' ) != -1){
var functionParts = functionName.split( '.' );
var classFunction = functionParts[1];
if (typeof window[functionParts[0]] === "function") {
var obj = new window[functionParts[0]]();
return obj['classFunction']; <!----- how to return function here?
}
}else{
if (typeof (window[functionName]) === "function") {
return window[functionName];
}
}
return false;
};
but I can't figure out how to return the function based on the class object and the function name?
It's possible that part or all of the problem is this:
return obj['classFunction'];
// ^^ Equivalent to obj.classFunction. In other words, reading a property
// called `classFunction`, not reading a property whose name is the value
// of the `classFunction` variable you set.
I haven't analyzed the code enough to fully understand it, but based on the context it seems that you'd mean this:
return obj[classFunction];

Jquery optionally add callbacks

I am trying to write a reusable Jquery form function. I need it to optionally assign callback functions depending on if the function is defined on the page or not.
Is this example I use the Success but would be done for all.
On Main JS File:
function gJs_AjaxCustomSubmit(ObjectContext) {
var AS='';
if (typeof AjaxSuccess == 'function') { AS = 'AjaxSuccess' }
$('#frm').ajaxSubmit({
success: AS, //callback functions
});
}
On the page, if AjaxSuccess function exists, then it would execute on the success callback. If it does not exist, there would be no error.
On normal pages:
function AjaxSuccess(response) {
alert(response);
}
I want to be able to define all the functions on my global JS like this, and then if needed I can just add the actual function to my pages and they will run.
function gJs_AjaxCustomSubmit(ObjectContext) {
var AStart='';
if (typeof AjaxStart == 'function') { AS = 'AjaxStart' }
var ASuccess='';
if (typeof AjaxSuccess == 'function') { AS = 'AjaxSuccess' }
var ABSend='';
if (typeof AjaxBeforeSend== 'function') { AS = 'AjaxBeforeSend' }
var AComplete='';
if (typeof AjaxComplete== 'function') { AS = 'AjaxSuccess' }
var ASt='';
if (typeof AjaxStop== 'function') { AS = 'AjaxStop' }
var AError='';
if (typeof AjaxError== 'function') { AS = 'AjaxError' }
$('#frm').attr("action", $(ObjectContext).data('path'));
$('#frm').ajaxSubmit({
dataType: 'html',
start: AStart, //callback functions
send: ABSend, //callback functions
complete: AComplete, //callback functions
stop: AjaxStop,
success: ASuccess, //callback functions
error: AError, //callback functions
});
}
Here is a clean reusable function that returns either desired function(if it exists) or an empty function if it doesn't.
$('#frm').ajaxSubmit({
start: getFunction('AStart'),
send: getFunction('ABSend'),
complete: getFunction('AComplete'),
//... //callback functions
});
function getFunction(name){
if (typeof window[name] == 'function'){
return window[name];
}
return function(){}; // or null/false
}
If the function passed as parameter by name does not exist, an empty callback will be returned, which will do nothing and not throw any errors.
I ended up using this.
function gJs_AjaxCustomSubmit(ObjectContext) {
//Add function to your page if needed
//AjaxStart
//AjaxBeforeSend
//AjaxComplete
//AjaxSuccess
//AjaxStop
//AjaxError
var DataType = 'html', AStart = '', ASuccess = '', ABSend = '', AComplete = '', AStop = '', AError = '';
if ($(ObjectContext).data('type')) {
DataType = $(ObjectContext).data('type');
}
if (typeof AjaxStart == 'function') { AStart = AjaxStart }
if (typeof AjaxBeforeSend == 'function') { ABSend = AjaxBeforeSend }
if (typeof AjaxComplete == 'function') { AComplete = AjaxComplete }
if (typeof AjaxSuccess == 'function') { ASuccess = AjaxSuccess }
if (typeof AjaxStop == 'function') { AStop = AjaxStop }
if (typeof AjaxError == 'function') { AError = AjaxError }
$('#frm').attr("action", $(ObjectContext).data('path'));
$('#frm').ajaxSubmit({
dataType: 'html',
start: AStart, //callback functions
send: ABSend, //callback functions
complete: AComplete, //callback functions
stop: AStop,
success: ASuccess, //callback functions
error: AError, //callback functions
});
}

Calling a custom jQuery plugin off the jQuery object itself

I am having trouble calling a jQuery plugin off the jQuery object itself. So rather than calling $(selector).myPlugin() I want to call $.myPlugin instead. For some reason it tells me that the function is undefined.
Here's my code:
(function ($) {
var _current = null;
var methods = {
init: function (options) {
_current = $('.rfgQuestionsWrapper').filter(function () {
return $(this).css('display') != 'none';
}).first();
console.log(_current);
$('.gaugeTitle').click(function (e) {
var rfgCode = $(this).parent().find('.gaugeWrapper').attr('id');
console.log(rfgCode);
showByCode(rfgCode);
return false;
});
},
showByCode: function (rfgCode) {
var target = $.utilities.filterById('.rfgQuestionsWrapper', rfgCode);
console.log(target);
_current.hide();
target.show();
}
};
$.fn.navigationManager = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.tooltip');
}
};
})(jQuery);
I must be doing something wrong because this is the first time I call a plugin this way... Any suggestions?
Look at that question: in jQuery what is the difference between $.myFunction and $.fn.myFunction?
Basically instead of $.fn.navigationManager = function(){} you write $.navigationManager = function(){}.

String to jQuery function

Overview
I am trying to find the jQuery function that matches a selection attribute value and run that function on the selection.
Example.
$('[data-store="' + key + '"]').each(function() {
var $callback = $(this).attr('data-filter');
if($callback != null) {
var fn = window['$.fn.nl2br()'];
if(jQuery.isFunction(fn)) {
$(this).fn();
}
}
$(this).setValue(value);
});
Problem 1
I'm not sure how to create a jQuery function call from string.
I know I can call the function like this, $(this)'onclick'; however I have no way to check if it exists before trying to call it.
Normally I could do this:
var strfun = 'onclick';
var fn = body[strfun];
if(typeof fn === 'function') {
fn();
}
This seems to fail:
var fn = window['$.fn.nl2br()'];
if(jQuery.isFunction(fn)) {
$(this).fn();
}
EDIT:
I seem to be having success doing this:
if($callback != null) {
var fn = $(this)[$callback]();
if( typeof fn === 'function') {
$(this)[$callback]();
}
}
Problem 2
Using jQuery.isFunction() how do you check if a methods exists? can you do this with jQuery.isFunction()?
Example
Declare function:
$.fn.nl2br = function() {
return this.each(function() {
$(this).val().replace(/(<br>)|(<br \/>)|(<p>)|(<\/p>)/g, "\r\n");
});
};
Test if function existe, these options fail:
jQuery.isFunction($.fn.nl2br); // = false
jQuery.isFunction($.fn['nl2br']()); //false
Functions in JavaScript are referenced through their name just like any other variables. If you define var window.foobar = function() { ... } you should be able to reference the function through window.foobar and window['foobar']. By adding (), you are executing the function.
In your second example, you should be able to reference the function through $.fn['nl2br']:
$.fn.nl2br = function() {
return this.each(function() {
$(this).val().replace(/(<br>)|(<br \/>)|(<p>)|(<\/p>)/g, "\r\n");
});
};
console.log(jQuery.isFunction($.fn['nl2br']));
See a working example - http://jsfiddle.net/jaredhoyt/hXkZK/1/
var fn = window['$.fn.nl2br']();
and
jQuery.isFunction($.fn['nl2br']);

Trying to understand this code (pub/sub library)

This is Peter Higgins's pub sub library: https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js
(function (d) {
var cache = {};
d.publish = function (topic, args) {
cache[topic] && d.each(cache[topic], function () {
this.apply(d, args || []);
});
};
d.subscribe = function (topic, callback) {
if (!cache[topic]) {
cache[topic] = [];
}
cache[topic].push(callback);
return [topic, callback];
};
d.unsubscribe = function (handle) {
var t = handle[0];
cache[t] && d.each(cache[t], function (idx) {
if (this == handle[1]) {
cache[t].splice(idx, 1);
}
});
};
})(jQuery);
I don't understand the logic and the functionality of publish:
cache[topic] && d.each(cache[topic], function () {
**this.apply(d, args || []);** //what is happening here?
});
What is the purpose of this part? except the fact that it publishes the event
In this context, the && is used as a shorthand for:
if (cache[topic]) {
d.each(cache[topic], function() { … });
}
This is because && (and ||) are short-circuiting, so if the left hand side evaluates to a false-ish value (or true-ish value, in the case of ||), the right hand side does not get evaluated.
For example:
> function foo(result) { console.log("foo"); return result; }
> function bar(result) { console.log("bar"); return result; }
> foo(false) && bar(true);
foo
false
Basically, you call each topic callback (if any) with args (if any arguments are passed). So you can:
$.subscribe('do_something', function(str) { alert(str + ' world!')});
$.subscribe('do_something', function(str) { console.log(str)});
$.publish('do_something', ['Hello']); // will alert Hello world! and output 'Hello' to console
cache[topic] && d.each(cache[topic], function () {
this.apply(d, args || []);
});
Applying for each element of d, if cache[topic] is defined, function, which calls the apply method of it with d argument, and args, or an empty array, if args is not defined.

Categories

Resources