hmmm, is it necessary to use this.functionName? I just
jQuery.plugin = function() {
var self = this;
function funcName() {
}
}; <-- small note
is this bad?
also, as a small note, I close with a semicolon, since you assign the
plugin "variable" the whole function, this seems like correct behaviour?
Andreas
On Jan 4, 2007, at 22:38 , Felix Geisendörfer wrote:
- Use your object function (jQuery.foo) only as a constructor, try to
put all methods into jQuery.foo.prototype (less stuff in
cunstructor ->
better OO design)
Obviously you can't access "self" from your methods, so you have to
design everything well enough to be able to work without "self"
Hmm but I wonder if it wouldn't be more pragmatic here to define
all functions in the constructor because having access to self
everywhere is a very nice option to have. I'm often doing this when
creating JS objects, and something like this could keep the code
quite readable:
jQuery.foo = function(element) {
var self = this;
this.constructor = function()
{
// Access self in callbacks, eg.
$(element).click(function(event)
{
self.handle(event);
});
}
this.handle = function()
{
alert('Hey, who clicked on me?');
}
this.constructor();
}
What do you think? (constructor might not work as a function name
due to a keyword conflict in JS, but you get the idea)
Personally I prefer wrapping all of my class code inside a function
over using prototype to extend it.
-- Felix
--------------------------
http://www.thinkingphp.org
http://www.fg-webdesign.de
Jörn Zaefferer wrote:
Briz schrieb:
I'm mostly interested in how to cleanly and reliably deal with scope
issues in callbacks.
I haven't read every detail of your example. Some suggestions:
- Do not extend Object.prototype. That can give you quite a lot of
trouble
- Try to gather all necessary callbacks inside the plugin method
(jQuery.fn.foo) or the constructor (jQuery.foo) and delegate to
methods
of your object inside the callbacks, while keeping the anonymous
functions for the callbacks as small as possible
- Avoid using each() in your code, and use a small plugin instead,
heavily reduces the need for anonymous functions inside your
object's code
- Use your object function (jQuery.foo) only as a constructor, try to
put all methods into jQuery.foo.prototype (less stuff in
cunstructor ->
better OO design)
A bit additional explanation. The code structure would look like
this:
jQuery.foo = function(element) {
// constructor code here
var self = this;
// access self in callbacks, eg.
$(element).click(function(event) {
self.handle(event);
});
}
jQuery.foo.prototype = {
// methods here, like handle()
}
Obviously you can't access "self" from your methods, so you have to
design everything well enough to be able to work without "self".
Hope that helps.
_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/
_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/