String to jQuery Function

Overview

I am trying to find a jQuery function that matches the value of a selection attribute and runs that function on 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 am not sure how to create a jQuery function call from a string.

I know that I can call a function like this, $ (this) 'onclick'; however, I can’t 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 like an error:

var fn = window['$.fn.nl2br()'];
if(jQuery.isFunction(fn)) {
    $(this).fn();
}

EDIT:

I seem to have been successful:

if($callback != null) {
    var fn = $(this)[$callback]();
    if( typeof fn === 'function') {
        $(this)[$callback]();
    }
}

Problem 2

Using jQuery.isFunction () how to check if methods exist? can you do this with jQuery.isFunction ()?

Example

Declare a function:

$.fn.nl2br = function() {
    return this.each(function() {
        $(this).val().replace(/(<br>)|(<br \/>)|(<p>)|(<\/p>)/g, "\r\n");
    });
};

Check if the function exists, these parameters do not work:

jQuery.isFunction($.fn.nl2br); // = false
jQuery.isFunction($.fn['nl2br']()); //false
+3
source share
2

JavaScript , . var window.foobar = function() { ... }, window.foobar window['foobar']. (), .

$.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']));

. - http://jsfiddle.net/jaredhoyt/hXkZK/1/

+4
var fn = window['$.fn.nl2br']();

jQuery.isFunction($.fn['nl2br']);
+1

All Articles