Jensen
Jensen

Reputation: 1723

how to let jQuery plugin function return intrinsic value

I am using the following pattern to write a jquery plugin, and I want the bar function to return intrinsic value, but it seems always to return $(this) instead.
Anything wrong with the code?

(function($){

    var Foo = function(elements, options){
    ... ...
    }


    Foo.prototype = {

        constructor: Foo,

        bar: function(){
            var value = ...        
            // do something here
            return value;
        },

    }

    $.fn.foo = function (option, kwargs){  
        return this.each(function(){ 
            var $this = $(this),
                data = $this.data('foo'),
                options = typeof option == 'object' && option

            if (!data) $this.data('foo', (data = new Foo(this, options)))
            if (typeof option == 'string') return data[option](kwargs)
        })            
    }


})(jQuery)

Upvotes: 2

Views: 2852

Answers (2)

rjz
rjz

Reputation: 16510

Nope, the code is correct. The problem is that it's currently set up to always return a jQuery selector (the return value of this.each). To return the result of your function instead, you could modify your function for $.fn.foo like so:

$.fn.foo = function (option, kwargs){  
    var retval = null;

    this.each(function(){ 
        var $this = $(this),
            data = $this.data('foo'),
            options = typeof option == 'object' && option

        if (!data) $this.data('foo', (data = new Foo(this, options)))
        if (typeof option == 'string') {
          retval = data[option](kwargs);
        }
    })

    if (!retval) {
      retval = this;
    }

    return retval;
}

Upvotes: 5

SLaks
SLaks

Reputation: 887449

In the outer function, you wrote returnthis.each(...);`.

this.each always returns the jQuery object you call it on (for chaining); it ignores the return value of the callback you pass it.

If you want to return a value from the callback, put that value in a variable, then return the variable after calling each. (this will work because each is not asynchronous).
You will need to figure out what to do if your method is called on a jQuery object with two elements; you may want get rid of the each call entirely.

Upvotes: 1

Related Questions