views:

53

answers:

2

I was wondering if it's possible to get to the name of the method that created a current array of elements.

I tried to find it in the jquery object itself, but I don't see a place where it could be stored.

Try to fill this in

$.fn.myfunc=function(){
//your brilliant idea here
return functname;
}

$('body').find('.a').myfunc(); //returns 'find'
$('body').children('.a').myfunc(); //returns 'children'
$('body').find('.a').next('div').myfunc(); //returns 'next'

//and if You're really awesome:
    $('body').find('.a').next('div').css('float','left').myfunc(); //returns 'next'
+1  A: 

This example isn't perfect, but it extracts the last operation for many situations (find, filter, children, next) - http://jsfiddle.net/X7LmW/3/ . Based off of the internals of jQuery.pushStack http://github.com/jquery/jquery/blob/master/src/core.js#L204

function last_operation( $$ ) {
    var selector = $$.selector,
        selector_cmpr;

    while ( ( selector_cmpr = remove_paren( selector ) ) != selector ) {
        selector = selector_cmpr;
    }

    var operations = selector.split('.'),
        is_find    = selector.replace(/, /, '').split(' ').length > 1,
        operation;

    if ( is_find ) {
        operation = 'find';
    } else if ( operations.length > 1 ) {
        operation = operations[ operations.length - 1 ].replace(/PAREN/, '')
    } else {
        operation = 'unknown';
    }
    return operation;

    function remove_paren( str ) {
        var str_cmpr = str.replace(/\([^()]+\)/, 'PAREN');
        return str_cmpr;
    }
}
BBonifield
Added new JSFiddle link with a more solid solution, account for sub-queries that contain spaces as well as class selectors.
BBonifield
That's a nice proof of concept. I would be satisfied with pointing out where to look for it, so this is just great!
naugtur
PS. I didn't accept the answer, because I'm waiting for the bounty option to pop up.
naugtur
After some tests I found out that Your is_find does not work properly. It's true whenever there's a find somewhere in the chain.
naugtur
A: 

Bounty goes to BBonified for finding the way.

This is my upgrade on the last_operation function. $() is recognized as .find() on purpose.

$.fn.lastop=function(){
var s=this.selector.replace(/^.*\.([a-zA-Z]+)\([^()]*\)[^ ()]*$|.*/,'$1');
return s?s:'find';
}

This was used here: http://www.jsfiddle.net/naugtur/rdEAu/

naugtur