-
General OOP Question
Hey all,
I know some of you may think this should go on the "Newbie" board, but this forum felt more appropriate since I'm not really a "n00b." I've gotten quite comfortable (in terms of what I do) with ActionScript 3.0 syntax/coding after a month of intense studying and now have a question regarding the idea of encapsulation or packaging. To practice my newly-learned language, I built a site for a company and it works great so far as I can tell, but I timeline-coded everything. I didn't place actions anywhere but on the main timeline's first frame, which, I think, is a good start, but I want to do my next site "properly" using packages and whatnot. My question is, where the hell do I start?! I've done some stuff using custom classes just for practice, but it was such a headache and most of the books I have use such silly examples that I just can't extrapolate to my projects.
I don't see much sense in creating classes for something I won't reuse, so after thinking of common core aspects of the sites I may build, I decided it'd make sense to develop something for media players. For the site I just built, I used XML to store the artist, filename, etc. and will likely do the same but in terms of "generic" classes, I don't know where to start. My thoughts ATM are to have one class that just loads the XML and maybe stores it into an XML List. Should that be the extent of it? If one of you could suggest a clever/logical approach to creating a generic media player, or even just list the names of class files you'd use (which I should be able to make sense of if the names are relatively descriptive), I'd really appreciate it. Sorry for the long post!
-
Senior Member
well you know there isn't anything really general about oop I mean after you figure out how to make packages then you have to learn to commuincate between classes using custom listeners that can pass variables to other classes or call methods and functions in other classes....here is how I do it and I'll bet others will disagree with me but here it is anyway..............I have a document class called Main which attaches to my .fla the fla only holds stage assets such as background maybe some images. I create all my buttons and stuff with actionscript. Then I attach all my "external" classes into main by importing the classes and then calling them if you will. here is what a typical Main document class looks like. Don't steal my code newbs! lol j/k
Keep in mind most of this code you wouldn't use it makes a connection to a media server and then after it connects it calls all the other classes.
PHP Code:
package Main{
import flash.display.*;
import flash.net.*;
import flash.events.NetStatusEvent;
import flash.events.*;
import flash.xml.*;
import flash.text.TextField;
import flash.external.ExternalInterface;
import NetConnections.NetConnections;
import NetConnections.NetStreams.CameraExample;
import NetConnections.NetStreams.NetStreamex;
import NetConnections.SharedObjects.SharedObjects;
import NetConnections.NetStreams.Audio;
import NetConnections.SharedObjects.VidSyncID;
import NetConnections.Send.Send;
import NetConnections.Call.Call;
import ClientInfo.ClientInfo;
import XMLang.Settings;
public class Admin_Main extends MovieClip {
public var camex:CameraExample;
public var nc1:NetConnections;
public var stream:NetStreamex;
private var so:SharedObjects;
private var send0:Send;
public var call0:Call;
private var audio:Audio;
private var getStream:String;
private var info:ClientInfo;
public var userName:*;
private var rePublishID1:Number;
private var oldInstanceID:*;
private var xmlSettings:Settings;
private var ipadd:*;
private var cliName1;
private var instanceID1:*;
private var pic:*;
public function Admin_Main():void {
start_btn.buttonMode=true;
start_btn.useHandCursor=true;
start_btn.x=195.0;
start_btn.y =195.3;
start_btn.addEventListener(MouseEvent.CLICK,GetInfo,false,0,true);
rec.y =2000;
play_it.y=2000;
rec_btn.y = 2000;
stop_btn.y = 2000;
replay_btn.y = 2000;
var rectangle:Shape = new Shape;
rectangle.graphics.lineStyle(4,0x00ff00);
rectangle.graphics.drawRect(79, 24, 322,242);
addChild(rectangle);
}
public function GetInfo(e:MouseEvent):void {
//xmlSettings = new Settings();
//xmlSettings.loader.addEventListener(Event.COMPLETE, onComplete);
onComplete();
}
public function onComplete(e:Event=null):void {
//var mainXML = new XML(xmlSettings.loader.data);
//ipadd = mainXML..item[0]..name.text() ;
//info = new ClientInfo();
//info.loader.addEventListener(Event.COMPLETE,Connect);
//xmlSettings.loader.removeEventListener(Event.COMPLETE,onComplete);
Connect();
}
public function Connect() {
//info.loader.removeEventListener(Event.COMPLETE,Connect);
//info.loader = URLLoader( e.target );
//userName = info.loader.data.modname;
userName ="Lori";
ipadd="www.somedomain.com";
nc1 = new NetConnections();
nc1.createNetConnection("rtmp://"+ipadd+"/someDir/"+userName+"_rec",userName,0);
nc1.addEventListener(NetStatusEvent.NET_STATUS, handleConnect);
}
private function handleConnect(e:NetStatusEvent):void {
if(e.info.code == "NetConnection.Connect.Closed"){
trace("////////closed");
ExternalInterface.call("alert", "The Camera Has Been Disconnected");
return;
}
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
so = new SharedObjects(nc1,userName);
call0 = new Call(nc1);
addChild(call0);
stream = new NetStreamex(nc1,userName);
camex = new CameraExample(stream,call0,userName,nc1,so.so0);
addChildAt(camex,8);
stream.iniList(camex);
audio = new Audio(stream,camex);
/*
for (var n:Number=0; n < numChildren; n++) {
var str5:DisplayObject=getChildAt(n);
trace(str5);
}
*/
}
}
}
-
I think that makes sense...mostly, haha. Not really actually, but the overall idea does. My main problem is that the client-specificness of my projects doesn't seem to allow for reusable code. For example, if you go to my most recent/only project: http://www.vinylwines.com/NewSite/index.html and click on "tunes" once it loads, the way the images are displayed and their functionality, etc. won't make sense in another project unless I find a way to "parametrize" the functions. I'll admit, I definitely, put too much code into each function, but for now, it works and somehow makes sense in my head. I know that even for timeline coding, it's better to use many functions with fewer individual roles than one function with a few dozen tasks. For example, my function that adds the buttons is huuuuuuge. Primarily because I need to a) figure out how many buttons I'll need, b) mathematically figure out a way to determine the proper row/column for each button, c) figure out the number of pages, d) determine how to exclusively display the nine buttons that can fit on the screen, and, finally, the important part, e) assign the button responses. I just can't find a way to compartmentalize this task. Ideally, I'd like to write a class/package that can perform all the necessary calculations using one or two parameters that I specify. For example, somehow create a "DynamicButtons" class that simply receives integers for how many items per row and per column (3 and 3) in my case, and does the rest itself, but could then do the same for 4 by 4, or even non-square displays. I dunno...I'll keep forking with it, but I'm wondering if, for what I do, it'd even be beneficial to use custom classes.
-
Welcome tonesofheresy in OOP's Concept.
Could you show any one of your function coding for any displayList?
On Object Oriented Programming, classes are built for reusing your code and all can driven from external data, which means according to your external configuration you can able to manipulate your design, functionality and other settings for your applications.
I best way I think is, you divide your existing TimeLine Code into a Document Class. and then re-divide it into sub-class from the Document Class according to your own understanding. This will help to grow on your own OOP knowledge. If it make sense to you then go for standardize mechanism of different suitable Patterns.
Try to divide your Code Block for each purpose like loading data, changing data, collecting data, sending data etc. All I am talking about generic purposes. So this can be fit for every projects.
arkitx
Last edited by arkitx; 08-07-2011 at 12:30 PM.
-
Hey arkitx,
This code will probably disgust you, haha, but here's my function for displaying the buttons on the "tunes" page of the site whose link I posted. I commented it as best I could to help you understand it. I'm using the TweenLite tween manager, in case that part doesn't make sense.
function addButtons(page:int):void
{
// Instructions to user
largeHldr.select_loading.text = "Please select an artist from the left."
for (var i:int = 0; i < totalArtists; i++)
{
// Determine which row and column a particular artist should be in based on the active page and the 3 x 3 arrangement of buttons
row = Math.floor(i/3) + 1 - (page - 1) * 3;
column = (i + 1) % 3;
if (column == 0) column = 3; // Zero remainder means column 3
// Set the horizontal position based on column number
switch(column)
{
case 1:
buttons[i].x = 85;
break;
case 2:
buttons[i].x = 238;
break;
case 3:
buttons[i].x = 391;
break;
}
// Set the vertical position based on row number
switch(row)
{
case 1:
buttons[i].y = 76;
break;
case 2:
buttons[i].y = 228;
break;
case 3:
buttons[i].y = 381;
break;
}
// Determine loop start and end index because there are multiple pages of artists
startIndex = (page * 9) - 9;
if (startIndex + 9 <= totalArtists) endIndex = startIndex + 9;
else endIndex = totalArtists;
// Display and animate buttons on current page
for(var j:int = startIndex; j < endIndex; j++)
{
buttons[j].scaleX = buttons[j].scaleY = 0;
addChild(buttons[j]);
TweenLite.to(buttons[j], 0.25, {scaleX: 1, scaleY: 1, ease:Expo.easeOut,
delay: (j - (page - 1) * 9) / 6});
buttons[j].addEventListener(MouseEvent.MOUSE_OVER, showName);
buttons[j].addEventListener(MouseEvent.MOUSE_OUT, hideName);
buttons[j].addEventListener(MouseEvent.CLICK, displayArtist);
}
}
}
This is only my function to actually display the buttons, I set them up in a different function. In terms of encapsulating my code, I think for this site I'm going to just avoid it since the hard part is done. But for the future, I'd like to properly build class files. One question, though, on the same site I linked you to, there's a record player that actually "plays" based on which song is selected and the needle moves from one end to the other over the duration of the whole playlist. It's not perfect cause the math is somewhat imprecise, but it's good enough for the client, thank God But for something like that, how would I set up classes? I've been reading a book on object-oriented programming, and it talks about drafting a UML version of the site but I just can't seem to think "object-orientedly." Maybe if I'd formally learned something, but I'm self-taught and just kinda learn things as the need arises. I want to start learning the right way though, and have two weeks still school starts, so I'm trying to pack this time with productivity. Any advice on the above function and/or record player issue? I'd like to at least envision how you smarter people would do things
-
heresy. OOP concepts apply to varying amounts depending on what you are building.
In the bad old days ppl used AS2 to build flash websites, and it isnt really object oriented at all. Flash websites are more proceedural than other projects which is why you havent needed to utilise OOP very much thus far.
If you were building a 'library' however, which only handles data rather than controls (DisplayObjects), then depending on the complexity of the library, OOP concepts may need to be applied religiously.
flos
-
Don't think me over smart. I appreciate your code which you showed in this function();
Document Class Function or Main TimeLine function.
Actionscript Code:
var AlbumPage:Array=new Array({list:5},{list:17},{list:9},{list:2});// data can comes from anywhere
var columnLength=4; var rowLength=3; var paddingCol=3; var paddingRow=40; var albumNum=0; var num=AlbumPage[albumNum].list;
var holder:MovieClip=new MovieClip(); addChild(holder); holder.x=20; holder.y=20;
albumList(num);
function albumList(list:int):void { if (holder.numChildren>0) { for (var r=holder.numChildren; r>0; r--) { holder.removeChildAt(0); } } var btn:Button; var totalList=list; for (var row=0; row<rowLength; row++) { for (var column=0; column<columnLength; column++) { if (list>0) { btn=new Button("artist"+albumNum,totalList-list); holder.addChild(btn); btn.x=(btn.width+paddingCol)*column; btn.y=(btn.height+paddingRow)*row; list--; } } } num=list; if (num>0) { //nextButton code godes here } }
Actionscript Code:
package { import flash.display.MovieClip; import flash.net.URLLoader; import flash.net.URLRequest; import flash.events.MouseEvent; import flash.events.Event; import flash.events.EventDispatcher;
public class Button extends MovieClip { public static const CLICKED:String="buttonClicked"; private var _linkImage:String; public function Button(link:String,img) { _linkImage="images/"+link+"/img"+img+".jpg"; buttonMode=true; addEventListener(MouseEvent.CLICK,mouseHandler); } private function mouseHandler(evt:MouseEvent):void{ trace("Image link: "+_linkImage); dispatchEvent(new Event(Button.CLICKED)); } } }
This is just a snippet of how you can shift your code concept.
Now try to shift your code from TimeLine to Document Class. Then after you can understand the need of classes.
arkitx
Last edited by arkitx; 08-10-2011 at 05:31 AM.
-
Flos and arkitx, thank you very much for all your help! Your explanations make a lot of sense. I think my main issue is knowing what ActionScript is capable of. The more I learn, the more I can simplify my code (obviously). Where I'm at now would be somewhat analogous to someone who didn't understand "for" loops and iterated through an array manually. Clearly it's not forbidden, but certainly not efficient. I think I need to just study the ActionScript help files and learn as many methods/properties as I can for things I use. I'd like to one day consider myself an efficient, effective, and capable programmer, but this is more of a hobby than anything, and I fear that I won't have time to learn it all once I start medical school. That's what happened before; I started on AS2 back in my first year of college, 8 years ago, just to make a website for my band and then put it on the back-burner till I had a reason to make another site, at which point, AS3 was deployed and I gave up. I had a request to build a site recently which is why I picked it back up, and I'm glad I did, but once this project's done, I may not have any clients and will end up forgetting what I know. If I'm not actively learning more about something, I tend to forget even what I already had pretty solid. I guess most people are like that, but looking back, I kinda wish I would have gone into computer science rather than medicine. Oh well...and actually, this short story brings me to another question. I briefly studied C# and Java and noticed many similarities between the two and AS3. Do you guys think it'd be fair to say that proficiency in AS3 will give me an upper-hand when really diving into C# and/or Java? If the answer is "yes," I may continue my studies along with school, so I'd appreciate any advice. Thanks again!
-
Dr.tonesofheresy, you might not bring my code into work. If it so then, make a rectangle MovieClip with a linkage name Button. Use the code in timeLine and also make the Button Class in the same Folder.
C++ JavaScript and Java has similar type of syntax. But the main thing is to learn the programming first then the syntax.
Best Wishes
arkitx
-
Total Universe Mod
Understanding Object Oriented Programming will make it easier to jump into any object oriented language. There are other types of languages and generally clean coding practices will make these easier to pick up too.
Don't get hung up on the "reusability" of code. That's just one nice feature of OOP but compartmentalizing is also a huge reason to make use of objects/classes. You've likely been fatigued in trying to keep everything straight when putting all the code in the timeline, breaking things down in to bite sized chunks makes this much easier. As a rule, put your classes in charge of one thing. You already instantiate classes like MovieClip and TextField. MovieClips handle graphics and frames well, they aren't burdened with streaming video or playing sound. TextFields handle text well, they are burdened with loading .swfs. Your classes should act the same way. You may have a MusicPlayer class that creates an instance of a PlayerControls class. PlayerControls would turn around and create instances of each of the buttons. Each of these classes only do things specific to that class. They are Lego's in a sense where they are all building blocks to a larger application.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|