Last active
August 29, 2015 14:11
-
-
Save michael/0af47cc83ed3f19cc489 to your computer and use it in GitHub Desktop.
tree-conversion.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
this.getSubjectsTree = function() { | |
var subjects = this.getEntities(); | |
// Build a map of parents referencing their kids | |
var map = {}; | |
_.each(subjects, function(subject) { | |
var parent = subject.parent || "root"; | |
if (!map[parent]) { | |
map[parent] = [ subject ]; | |
} else { | |
map[parent].push(subject); | |
} | |
}); | |
function getChildren(parent) { | |
var res = []; | |
var subjects = map[parent]; | |
if (!subjects) return res; // exit condition | |
_.each(subjects, function(subj) { | |
var entry = { | |
id: subj.id, | |
text: subj.name, | |
children: getChildren(subj.id) // get children for subj | |
}; | |
res.push(entry); | |
}); | |
return res; | |
} | |
return getChildren("root"); | |
}; | |
}; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
initilize: function() { | |
this.subjectCollection.on('model-update', this.onNodeUpdate); | |
}, | |
prepareViews: function() { | |
this.subjectViews = {}; | |
_.each(this.model.subjectCollection, function(subject) { | |
this.subjectViews[subject.id] = new SubjectView(subject).render(); // <li class="subject-view">alsidjfailsdjf laksd </li> | |
}, this); | |
}; | |
// does affect hierarchy | |
addSubject: function() { | |
// model creation | |
var subj = ; | |
this.subjectViews[subj.id] = new SubjectView(subject).render(); | |
this.updateHierachachy(); | |
}; | |
// doesnt affect hierarchy | |
onNodeUpdate: function(subj) { | |
this.subjectViews[subj.id].render() // re-render | |
}, | |
updateHierachachy = function() { | |
function renderChildren(parent) { | |
listEl = $('<ul>'); | |
var subjects = map[parent]; | |
if (!subjects) return res; // exit condition | |
_.each(subjects, function(subj) { | |
// var listItem = renderListItem(subj); | |
var listItemEl = this.subjectViews[subj.id].el; | |
var childList = renderChildren(subj.id); | |
listItemEl.appendChild(childList); | |
listEl.appendChild(listItemEl); | |
}); | |
return listEl; | |
} | |
var listEl = renderChildren("root"); | |
}, | |
render: function() { | |
this.prepareViews(); | |
this.updateHierachachy(); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment