js backbone graph node - should I use a backbone collection?
var GraphNode = Backbone.Model.extend({ | |
defaults: { parents: [], children: [], name: 'node' }, | |
addparent: function(parent) { | |
if (!this.hasparent(parent)) { | |
this.get('parents').push(parent) | |
this.trigger('addparent',parent) | |
parent.addchild(this) | |
var self = this; | |
parent.bind('destroy',function() { self.removeparent(parent) } ) | |
return parent | |
} | |
return undefined | |
}, | |
addchild: function(child) { | |
if (!this.haschild(child)) { | |
var children = this.get('children') | |
children.push(child) | |
this.set({children: children}) | |
this.trigger('addchild',child) | |
child.addparent(this) | |
var self = this; | |
child.bind('destroy',function() { self.removechild(child) } ) | |
return child | |
} | |
return undefined | |
}, | |
bindchild: function(event,f) { | |
this.bind('addchild',function(child) { | |
child.bind(event,f) | |
}) | |
this.bind('removechild',function(child) { | |
child.unbind(event,f) | |
}) | |
}, | |
unbindchild: function(event,f) { | |
// not today :) | |
}, | |
removeparent: function(searchparent) { | |
var removed = false | |
var self = this | |
this.set({ parents : _.reject(this.get('parents'),function(parent) { if (parent == searchparent) { searchparent.removechild(self); removed = true; return true } })}) | |
if (removed) { this.trigger('removeparent',searchparent) } | |
}, | |
removechild: function(searchchild) { | |
var removed = false | |
var self = this | |
this.set({children: _.reject(this.get('children'),function(child) { if (child == searchchild) { searchchild.removechild(self); removed = true; return true } })}) | |
if (removed) { this.trigger('removechild',searchchild) } | |
}, | |
hasparent: function(searchparent) { | |
return _.find(this.get('parents'),function(parent) { return (parent === searchparent) }) | |
}, | |
haschild: function(searchchild) { | |
return _.find(this.get('children'),function(child) { return (child === searchchild) }) | |
}, | |
parent: function() { | |
var parents = this.get('parents') | |
if (parents.length) { return parents[0] } | |
}, | |
child: function() { | |
var children = this.get('children') | |
if (children.length) { return children[0] } | |
}, | |
parents: function() { | |
return this.get('parents') | |
}, | |
children: function() { | |
return this.get('children') | |
}, | |
name: function() { | |
return this.get('name') | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment