Floris
Floris

Reputation: 3127

Access class this from each in a jQuery plugin widget

I would like to access the this.options variable from within a each loop. I am using the jQuery ui Widget Factory pattern.

// etc..
,
_buildThumbs: function() {

$.each(this.options.photos, function( i, photo ) {

    // Modify template html...
    // ...


    $(this.options.containerThumbsClass).append( thumbnail );
    // Oh my, this.options is undefined :(
});

So what is the best way to access the options? Maybe pass the class reference to the each method? Thanks.

Upvotes: 0

Views: 90

Answers (1)

Ivan
Ivan

Reputation: 789

That's because jquery 'each' function has it's own context. Try this:

_buildThumbs: function() {
var localOptionsVariable = this.options;
$.each(this.options.photos, function( i, photo ) {    
    $(localOptionsVariable.containerThumbsClass).append( thumbnail );
});

But the best way is to have a function within your plugin that will return options object. For instance, you can store options in the root element data.

[Edited]

(function ($) {
    var PLUGIN_NAMESPACE = "your-plugin-namespace";
    var defaultOptions = {
        someOption: 'DefaultOptionValue'
    };
    var isIE = /msie/.test(navigator.userAgent.toLowerCase());

    $.extend($.fn, {
        setTestPlugin: function (options) {
            options = $.extend({}, defaultOptions, options);
            return this.each(function () {
                var $container = $(this);
                $container.addClass(PLUGIN_NAMESPACE);
                $container.data("options", options);

                $container.val('Plugin applied!')
                $container.on('click', function(){
                  $container.someOtherFunction();
                });
            });
        },
        getOptions: function () {
            return this.data("options");
        },
        someOtherFunction: function () {
            var $container = this;
            var options = $container.getOptions();
            $.each([0], function(i, item){
              alert(options.someOption);
            });
            
        },
    });

})(jQuery);

$('#textBoxNewOption').setTestPlugin({someOption: 'New option value'});
$('#textBoxDefault').setTestPlugin();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="textBoxDefault" />
<input type="text" id="textBoxNewOption" />

Upvotes: 2

Related Questions