Craig Burton
Craig Burton

Reputation: 188

How can I pass an object reference into the constructor of another object in mootools?

I've looked around here, and pretty much everywhere else I can think of, but I can't find a solution to my problem, so here it is:

In my current project, I have a class that instantiates an object as part of its constructor, passing itself in so the child object will have a reference to its parent. Ideally, anyway. What ends up happening, though, is that the child gets a static view of the parent object. Here's an example of what I mean:

var myParentClass = new Class({
    name: '',
    child: null,

    initialize: function(){
        this.name = 'fred';
        this.child = new myChildClass({ parent: this });
        this.name = 'george';
        this.setFeedback('feedback1');
        this.child.setFeedback('feedback2');
    },

    setFeedback: function(id){
        $(id).set('html',this.name);    
    }

    });

var myChildClass = new Class({

    Implements: [Options],

    options: {
        parent: null,
    },

    initialize: function(options){
      this.setOptions(options);   
    },

    setFeedback: function(id){
        this.options.parent.setFeedback(id);       
    }
});


var a = new myParentClass();

​In this example, feedback1's contents would be 'george', and we'd expect that feedback2's contents would be the same. However, it's not. It's 'fred' because it has a static view of the parent, whose name property changed AFTER the object was passed in as a parameter. For your further enjoyment, I've made a jsfiddle to illustrate the point.

So the question is this: Is there any way I can get a child object to have a real actual reference to its parent, or am I doomed to only ever have a static view?

Upvotes: 1

Views: 467

Answers (1)

Dimitar Christoff
Dimitar Christoff

Reputation: 26165

this is because the setOptions method dereferences properties via an Object.merge into a new Object, cloning them into the local prototype of the child instance.

https://github.com/mootools/mootools-core/blob/master/Source/Class/Class.Extras.js#L110

change the constructor function to accept another argument, parent and statically store this.parent = parent, then call from that.

incidentally, don't use .parent as this is kind of reserved for when you extend classes in mootools :)

Upvotes: 4

Related Questions