ojbravo
ojbravo

Reputation: 45

Undefined Parent Object

I'm writing a Family Tree app and I'm having trouble connecting a child with a parent dynamically. I keep getting an error that the parent is undefined. As the same function was used to create the parent, I'm lost as to how to identify the parent other than passing it through a variable name when the function is called again.

Huge thanks to anyone that can point me in the right direction. I'm obviously not very well versed in javascript.

Update: I was able to solve the problem by assigning each of the function calls to an appropriately names variable. Thanks to @Oriol's help below!

var rafael_bravo = addFamilyMember("rafael_bravo", "Rafael Bravo", "-", "-", "-", god, "GeneralPartner");
var calixta_otero = addFamilyMember("calixta_otero", "Calixta Otero", "-", "-", "-", rafael_bravo, "LimitedPartner");
var omar_bravo = addFamilyMember("omar_bravo", "Omar Bravo", "-", "-", "-", rafael_bravo, "LimitedPartner");


    function addFamilyMember (child,name,dob,dod,img,parent,link) {

                    child = new primitives.orgdiagram.ItemConfig();
                    child.name = name;
                    child.birth = dob;
                    child.death = dod;
                    child.image = "includes/images/" + img + ".png";
                    child.templateName = "familyTemplate";
                    parent.items.push(child);

                    jQuery(".basicdiagram").orgDiagram("update", primitives.orgdiagram.UpdateMode.Refresh);
                    return child;
                }

Upvotes: 1

Views: 901

Answers (1)

Oriol
Oriol

Reputation: 288100

You could use

var names = {};
function addFamilyMember (id,name,dob,dod,img,parentId,link) {
    var child = new primitives.orgdiagram.ItemConfig();
    child.name = name;
    child.birth = dob;
    child.death = dod;
    child.image = img ? "includes/images/" + img + ".png" : "";
    child.templateName = "familyTemplate";
    names[id] = child;
    names[parentId].items.push(child);
    jQuery(".basicdiagram").orgDiagram("update", primitives.orgdiagram.UpdateMode.Refresh);
    return child;
}
addFamilyMember("rafael_bravo", "Rafael Bravo", "-", "-", "", "god", "GeneralPartner");
addFamilyMember("calixta_otero", "Calixta Otero", "-", "-", "", "rafael_bravo", "LimitedPartner");
addFamilyMember("omar_bravo", "Omar Bravo", "-", "-", "", "rafael_bravo", "LimitedPartner");

Also note that if you use "-" as img, browser will try to download includes/images/-.png, so better use something falsy (like empty string "", or void(0), or false) and then check it. I have used an empty string, but some browsers will try to download current page as image, so better check child.image when you create the image.

Upvotes: 1

Related Questions