Question

I create JQuery Widgets something like this

<script type="text/javascript">
(function ($) {
        $.widget("cb.bacon", {
            _create: function() {
                var self = this,
                    o = self.options,
                    el = self.element;

                 // Some code

            },

            _bacon: function() {
                var self = this,
                    o = self.options,
                    el = self.element;

                 // Some code
            },

            _smokey: function() {
                var self = this,
                    o = self.options,
                    el = self.element;

                 // Some code
            } 
        });
    })(jQuery);                 
</script>

I invariably end up having to declare self, options, element in each function that I create.

Is there some fundimental understanding that I'm missing or do I really have to do that all the time?

Was it helpful?

Solution

You don't have to do that at all, that is only to make it easier to access those inside the function.

The self variable is useful when you are using a callback in a jQuery function, where this would be set to the element that you are acting upon. For example:

$('.bacon').each(function(){ $(this).css('background', self.getBackground()); });

The variables o and el just makes for less typing. If you have the varaible self, or the reference this unchanged, you can access the options and element properties from the object directly.

OTHER TIPS

You need to declare these things each time since you are using an object literal. You could wrap the object literal as a function call and achieve what you want that way.

<script type="text/javascript">
function makeTheBacon() {
    var self = this;
    var o = self.options;
    var el = self.element;

    self._create = function() {...};
    self._bacon = function() {...};
    self._smokey = function() {...};
    return self;
}

(function ($) {
    $.widget("cb.bacon", makeTheBacon());
})(jQuery);
</script>

There is also a questions that touches on this also by using functions in the object literal here, but that seemed overly verbose considering your original question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top