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
self
variable is useful when you are using a callback in a jQuery function, wherethis
would be set to the element that you are acting upon. For example:The variables
o
andel
just makes for less typing. If you have the varaibleself
, or the referencethis
unchanged, you can access theoptions
andelement
properties from the object directly.