Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 958
Levi Putna Avatar asked Sep 19 '26 05:09

Levi Putna


1 Answers

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/

like image 181
jaredhoyt Avatar answered Sep 21 '26 18:09

jaredhoyt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!