Skip to content

Instantly share code, notes, and snippets.

@schovi
Created April 12, 2013 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schovi/5374759 to your computer and use it in GitHub Desktop.
Save schovi/5374759 to your computer and use it in GitHub Desktop.
CanJS Live Value Control
var stringify = function(obj) {
if(obj === undefined || obj === null) {
} else if(typeof obj === "object") {
if(obj instanceof can.Observe) { // Get native object or array from Observe or Observe.List
obj = obj.attr()
} else { // Clone object to prevent change original values
obj = can.isFunction(obj.slice) ? obj.slice() : can.extend({}, obj)
}
// Convert each object property or array item into stringified new
can.each(obj, function(val, prop) { obj[prop] = stringify(val) })
} else if(can.isFunction(obj.toString)) {
obj = obj.toString()
}
return obj
}
return can.Control('LiveValue', {
init: function(el) {
var opt = this.options
// Todo refactor
if(opt.obj && opt.prop) {
// Fine
} else if(opt.obj && !opt.prop) {
var elName = el.attr('name')
if(elName) {
opt.prop = el.attr('name')
this.on()
} else {
console.warn("Cant initialize LiveValue control without option 'prop' or element name attribute")
this.destroy()
return
}
} else if(!opt.compute) {
console.warn("Cant initialize LiveValue control without 'obj' or 'compute'")
this.destroy()
return
}
this.set()
},
"{obj} {prop}": "set",
"{compute} change": "set",
set: function() {
var opt = this.options,
el = this.element,
val;
if(this.hasObj()) {
val = opt.obj.attr(opt.prop);
} else if(this.hasCompute()) {
val = opt.compute()
}
el.val(stringify(val))
},
"change": function() {
var opt = this.options,
val = this.element.val();
if(this.hasObj()) {
opt.obj.attr(opt.prop, val)
} else if(this.hasCompute()) {
opt.compute(val)
}
},
"keydown": function(el, ev) {
if(ev.keyCode == 13) {
this.element.trigger('change')
}
},
hasObj: function() {
var opt = this.options;
return opt.obj && opt.prop;
},
hasCompute: function() {
return this.options.compute;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment