Skip to content

Instantly share code, notes, and snippets.

@michael
Last active August 29, 2015 14:11
Show Gist options
  • Save michael/0af47cc83ed3f19cc489 to your computer and use it in GitHub Desktop.
Save michael/0af47cc83ed3f19cc489 to your computer and use it in GitHub Desktop.
tree-conversion.js
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");
};
};
{
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