...

View Full Version : Prototype - Class creation and organization



polygone
07-15-2009, 09:15 PM
Hello all. I've made classes, in prototype, for various projects and have now come to a point where I am a bit stuck. In the past I had trouble with scoping issues and having to bind the current object to the this keyword, so I can use it in 'lexical closures'(not sure if that's the correct terminology).

Example:


var Example = Class.create({
initialize : function() {
this.newElement = $(something);
},
doStuff: function(){
//I know this is a ridiculous example, but I'm trying to be concise
$R(1..10).times(function(){
alert(this.newElement);
}.bind(this));
}
});


OK, so notice how I have to bind this to the .times iterator, otherwise I get the window object and not my class.

Well, I now have quite the large class and would like to organize it better for my own sanity. I was attempting to do something like this:



var Example = Class.create({
initialize : function() {
this.newElement = $(something);

},

utilities: {
doStuff: function(){
alert(this.newElement);
}
}

});


So, at some point I can call it like this:



var example = new Example();
example.utilities.doStuff();


The problem is using the 'this' keyword inside of that doesn't work out.
I tried this with no luck:


var Example = Class.create({
initialize : function() {
this.newElement = $(something);

},

utilities: {
doStuff: function(){
alert(this.newElement);
}
}.bind(this)

});


I get a syntax error, at this point.

Can someone steer me in the right direction? I know I've seen libraries do this before and I think the prototype classing system should have some way to do it.


[Edit] Sorry, I didn't realize there was a special section for frameworks. If an admin would be so kind as to move it for me, that would be great. :)

fside
07-16-2009, 06:32 AM
While you don't capitalize it, you're talking about Stephenson's Prototype, yes, not merely about Javascript prototype objects?

While not a "framework", neither is JQuery, there is a forum for these questions called - Javascript frameworks.

polygone
07-16-2009, 02:02 PM
Yes, fside. I am talking about Prototype the framework. ...and yes I didn't see the prototype section, originally.

Any input?

polygone
07-16-2009, 05:12 PM
http://pastie.org/548222

Here's a solution that worked for me.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum