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?
You don't have to do that at all, that is only to make it easier to access those inside the function.
The
selfvariable is useful when you are using a callback in a jQuery function, wherethiswould be set to the element that you are acting upon. For example:The variables
oandeljust makes for less typing. If you have the varaibleself, or the referencethisunchanged, you can access theoptionsandelementproperties from the object directly.