Skip to content

Instantly share code, notes, and snippets.

@mrunderhill89
Created March 13, 2015 06:58
Show Gist options
  • Save mrunderhill89/1841c9079b7f6a7f72fa to your computer and use it in GitHub Desktop.
Save mrunderhill89/1841c9079b7f6a7f72fa to your computer and use it in GitHub Desktop.
Simple auto-updating connectors between two objects. Compatible with mixin.js and interface.js
define(['underscore', 'bacon_extra', 'interface', 'mixin'],
function(_, Bacon, Interface, Mixin){
var i_Association = new Interface({
methods:["reflect", "get_data"]
});
var One = Mixin.implement({
interface: i_Association,
default_mixins: ["get_data", "set_data"],
initialize: function(params){
this.set_data = Bacon.fromClosure(function(data){
this.data = data.toProperty(params.data);
}.bind(this),this);
this.set_target = Bacon.fromClosure(function(target){
this.target = target.skipDuplicates().scan(undefined,
function(prev, next){
if (prev){prev.reflect(null);}
if (next){next.reflect(this);}
return next;
}
);
}.bind(this),this);
},
methods:{
reflect: function(that){
return this.set_target(that);
},
get_data: function(){
return this.data;
}
}
});
var Many = Mixin.implement({
interface: i_Association,
default_mixins: ["get_data", "set_data"],
initialize: function(params){
this.set_data = Bacon.fromClosure(function(data){
this.data = data.toProperty(params.data);
}.bind(this),this);
Bacon.fromClosure(function(ops){
this.children = ops.scan({},
function(children, op){
return op(children) || children;
}
);
this.children.onValue();
var parent = this;
this.target = new Bacon.Bus();
this.target.onValue(function(params){
var child = params.child;
var id = (params.id || _.uniqueId("association_"));
var parent = this;
ops.push(function(children){
this.data.onValue(function(data){
if (!children[id]){
children[id] = new One({data:data});
};
children[id].set_data(data);
});
children[id].set_target(child);
child.reflect(children[id]);
}.bind(this));
}.bind(this));
this.set_target = function(child,id){
this.target.push({
child:child,
id:id
});
return this;
}.bind(this);
}.bind(this));
},
methods:{
reflect: function(that){
return this.set_target(that);
}
}
});
return {
One: One,
Many: Many
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment