mrbm
mrbm

Reputation: 2194

why jquery plugin function is always returning object instead of a string?

here is my code for a custom jquery plugin :

(function($){
    $.fn.extend({
        getmyValue : function(){
        return this.each(function() {
                return this.myVal;
        });
        },
        initPlugin : function(){
        return this.each(function() {
                this.myVal='Some results';
        });
        }
    });
})(jQuery);

when i run this code :

$(document).ready(function() {

$("#div").initPlugin();
alert($("#div").getmyValue());
});

the returned value is not a plain string as supposed but an object ( $("#div") is returned )

what i can't figure out is why the return chaining is not working ?

Upvotes: 3

Views: 2007

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

Because the return value of each is the object on which you called each. The return value of the function each calls is used to determine whether to stop looping (that is, the iteration function can return false to stop looping — docs link).

It's unclear from your code what you really want to do in getmyValue; return a value you've stored on the jQuery instance itself? Return the myVal stored on the first contained element? Return an array of the myVal values from all the contained elements?

If you meant a myVal stored on the jQuery instance by your plugin:

getmyValue : function(){
    // Here, `this` is the jQuery instance on which `getmyvalue` was called
    return this.myVal;
},

If you meant the myVal on the first element (note that it's a raw DOM element in the typical case):

getmyValue : function(){
    // Here, `this` is the jQuery instance on which `getmyvalue` was called.
    // `this[0]` is the first matched element (a raw DOM element, typically).
    // Note we check before accessing it to see if it's there, since a jQuery
    // instance may have matched zero elements.
    return this[0] ? this[0].myVal : undefined;
},

If you meant an array of the myVal values from all the matched elements (again, these will be raw DOM elements in the typical case):

getmyValue : function(){
    // Here, `this` is the jQuery instance on which `getmyvalue` was called.
    return this.map(function() {
            // Here, though, `this` one of the elements wrapped by the jQuery,
            // instance typically a raw DOM element. (Each of them in a loop.)
            return this.myVal;
    }).get();
},

...which uses map to get a jQuery-wrapped array of the values, and then get to get the raw array from it.

Upvotes: 4

Phil Klein
Phil Klein

Reputation: 7514

You're returning the result of this.each() rather than this.myVal:

getmyValue: function() {
    return this.myVal;
}

Upvotes: 1

kwelch
kwelch

Reputation: 2469

The return of the .each is an object. If you replace that with .map then your code will return a comma delimited list of values.

jQuery Map

Upvotes: 0

Related Questions