views:

128

answers:

2

Hi. I have a Main.fla (controlled by Main.as) that has a child named Slide (a Movieclip controlled by another class, Slide.as).

Sometimes, my Slide object have to call the method "nextSlide" on his father, Main object. To do this I tried "this.parent.nextSlide()", but I got this error:

1061: Call to a possibly undefined method nextSlide through a reference with static type flash.display:DisplayObjectContainer.

So, I tried pass the father object by constructor:

var slide:Slide = new Slide(this)

And, on my Slide class, a used this:

public function Slide(myParent:Main) {
   this.myParent = myParent;
}
...
myParent.nextSlide();

Is this correct? Is this dependency injection?

Thank you.

+1  A: 

It is correct in the sense that it will work. But you can also cast the parent property to the Main type, after which you can call the nextSlide method:

Main(this.parent).nextSlide();

This way you tells the compiler to treat the parent property as a Main object. If the parent property is not a Main object you will get an error at run-time.

I wouldn't call what you are doing dependency injection.

Markus Johnsson
+2  A: 

In my opinion: yes it is. This is probably the most basic form of dependency injection, but it still is injecting a depency in the class instance. I quote from James Shore´s article "Dependency Injection Demystified":

Dependency injection means giving an object its instance variables. Really. That's it.

see: http://jamesshore.com/Blog/Dependency-Injection-Demystified.html

There is of course a lot more to dependency injection, there are large frameworks like Spring built around this concept. A bit unispired, but still always a good read: the wikipedia article about DI http://en.wikipedia.org/wiki/Dependency%5Finjection there is also a more complex article about this from Martin Fowler, its older and to be honest, when I read it the first time, I had no idea what he is talking about http://martinfowler.com/articles/injection.html

Max