Skip to content

Instantly share code, notes, and snippets.

@cdaringe
Last active August 29, 2015 14:15
Show Gist options
  • Save cdaringe/b6443573c8ae0fb9ca57 to your computer and use it in GitHub Desktop.
Save cdaringe/b6443573c8ae0fb9ca57 to your computer and use it in GitHub Desktop.
requirebin sketch
var FormView = require('ampersand-form-view');
var SelectView = require('ampersand-select-view');
var MyForm = FormView.extend({
validCallback: function (valid) {
if (valid) {
console.log('The form is valid!');
} else {
/**
* THIS IS EXECUTED on first render
* caps are friendly, just for attention drawing :)
*/
console.log('The form is not valid!');
}
},
fields: [
new SelectView({
autoRender: true,
// parent: this,
label: 'test1',
name: 'test2',
value: 'SOME INITIAL VALUE...',
options: ['blue', 'orange', 'red'],
tests: [],
unselectedText: "Add canned response",
required: false
})
]
});
var myForm = new MyForm();
document.body.appendChild(myForm.el);
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){(function(){var root=this,breaker={},nativeForEach=Array.prototype.forEach,hasOwnProperty=Object.prototype.hasOwnProperty,slice=Array.prototype.slice,idCounter=0;function miniscore(){return{keys:Object.keys,uniqueId:function(prefix){var id=++idCounter+"";return prefix?prefix+id:id},has:function(obj,key){return hasOwnProperty.call(obj,key)},each:function(obj,iterator,context){if(obj==null)return;if(nativeForEach&&obj.forEach===nativeForEach){obj.forEach(iterator,context)}else if(obj.length===+obj.length){for(var i=0,l=obj.length;i<l;i++){if(iterator.call(context,obj[i],i,obj)===breaker)return}}else{for(var key in obj){if(this.has(obj,key)){if(iterator.call(context,obj[key],key,obj)===breaker)return}}}},once:function(func){var ran=false,memo;return function(){if(ran)return memo;ran=true;memo=func.apply(this,arguments);func=null;return memo}}}}var _=miniscore(),Events;Events={on:function(name,callback,context){if(!eventsApi(this,"on",name,[callback,context])||!callback)return this;this._events||(this._events={});var events=this._events[name]||(this._events[name]=[]);events.push({callback:callback,context:context,ctx:context||this});return this},once:function(name,callback,context){if(!eventsApi(this,"once",name,[callback,context])||!callback)return this;var self=this;var once=_.once(function(){self.off(name,once);callback.apply(this,arguments)});once._callback=callback;return this.on(name,once,context)},off:function(name,callback,context){var retain,ev,events,names,i,l,j,k;if(!this._events||!eventsApi(this,"off",name,[callback,context]))return this;if(!name&&!callback&&!context){this._events={};return this}names=name?[name]:_.keys(this._events);for(i=0,l=names.length;i<l;i++){name=names[i];if(events=this._events[name]){this._events[name]=retain=[];if(callback||context){for(j=0,k=events.length;j<k;j++){ev=events[j];if(callback&&callback!==ev.callback&&callback!==ev.callback._callback||context&&context!==ev.context){retain.push(ev)}}}if(!retain.length)delete this._events[name]}}return this},trigger:function(name){if(!this._events)return this;var args=slice.call(arguments,1);if(!eventsApi(this,"trigger",name,args))return this;var events=this._events[name];var allEvents=this._events.all;if(events)triggerEvents(events,args);if(allEvents)triggerEvents(allEvents,arguments);return this},stopListening:function(obj,name,callback){var listeners=this._listeners;if(!listeners)return this;var deleteListener=!name&&!callback;if(typeof name==="object")callback=this;if(obj)(listeners={})[obj._listenerId]=obj;for(var id in listeners){listeners[id].off(name,callback,this);if(deleteListener)delete this._listeners[id]}return this}};var eventSplitter=/\s+/;var eventsApi=function(obj,action,name,rest){if(!name)return true;if(typeof name==="object"){for(var key in name){obj[action].apply(obj,[key,name[key]].concat(rest))}return false}if(eventSplitter.test(name)){var names=name.split(eventSplitter);for(var i=0,l=names.length;i<l;i++){obj[action].apply(obj,[names[i]].concat(rest))}return false}return true};var triggerEvents=function(events,args){var ev,i=-1,l=events.length,a1=args[0],a2=args[1],a3=args[2];switch(args.length){case 0:while(++i<l)(ev=events[i]).callback.call(ev.ctx);return;case 1:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1);return;case 2:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2);return;case 3:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2,a3);return;default:while(++i<l)(ev=events[i]).callback.apply(ev.ctx,args)}};var listenMethods={listenTo:"on",listenToOnce:"once"};_.each(listenMethods,function(implementation,method){Events[method]=function(obj,name,callback){var listeners=this._listeners||(this._listeners={});var id=obj._listenerId||(obj._listenerId=_.uniqueId("l"));listeners[id]=obj;if(typeof name==="object")callback=this;obj[implementation](name,callback,this);return this}});Events.bind=Events.on;Events.unbind=Events.off;Events.mixin=function(proto){var exports=["on","once","off","trigger","stopListening","listenTo","listenToOnce","bind","unbind"];_.each(exports,function(name){proto[name]=this[name]},this);return proto};if(typeof define==="function"){define(function(){return Events})}else if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports){exports=module.exports=Events}exports.BackboneEvents=Events}else{root.BackboneEvents=Events}})(this)},{}],2:[function(require,module,exports){module.exports=require("./backbone-events-standalone")},{"./backbone-events-standalone":1}],3:[function(require,module,exports){var arr=[];var each=arr.forEach;var slice=arr.slice;module.exports=function(obj){each.call(slice.call(arguments,1),function(source){if(source){for(var prop in source){obj[prop]=source[prop]}}});return obj}},{}],"ampersand-form-view":[function(require,module,exports){if(typeof window!=="undefined"){window.ampersand=window.ampersand||{};window.ampersand["ampersand-form-view"]=window.ampersand["ampersand-form-view"]||[];window.ampersand["ampersand-form-view"].push("2.2.0")}var BBEvents=require("backbone-events-standalone");var extend=require("extend-object");var result=function(obj,prop){if(typeof obj[prop]==="function")return obj[prop]();return obj[prop]};function FormView(opts){opts=opts||{};this.el=opts.el;this.validCallback=opts.validCallback||this.validCallback||function(){};this.submitCallback=opts.submitCallback||this.submitCallback||function(){};if(opts.data)this.data=opts.data;if(opts.model)this.model=opts.model;this.clean=opts.clean||function(res){return res};this.valid=false;this.preventDefault=opts.preventDefault===false?false:true;this.autoAppend=opts.autoAppend===false?false:true;this._fieldViews={};this._fieldViewsArray=[];this.render();(opts.fields||result(this,"fields")||[]).forEach(this.addField.bind(this));if(this.initialize)this.initialize.apply(this,arguments);setTimeout(function(){this.checkValid(true)}.bind(this),0)}extend(FormView.prototype,BBEvents,{data:null,model:null,fields:null,addField:function(fieldView){this._fieldViews[fieldView.name]=fieldView;this._fieldViewsArray.push(fieldView);if(this.fieldContainerEl){fieldView.parent=this;fieldView.render();this.fieldContainerEl.appendChild(fieldView.el)}},removeField:function(name){var field=this.getField(name);if(field){field.remove();delete this._fieldViews[name];this._fieldViewsArray.splice(this._fieldViewsArray.indexOf(field),1)}},getField:function(name){return this._fieldViews[name]},setValid:function(now,forceFire){var prev=this.valid;this.valid=now;if(prev!==now||forceFire){this.validCallback(now)}},checkValid:function(forceFire){var valid=this._fieldViewsArray.every(function(field){return field.valid});this.setValid(valid,forceFire);return valid},beforeSubmit:function(){this._fieldViewsArray.forEach(function(field){if(field.beforeSubmit)field.beforeSubmit()})},update:function(field){this.trigger("change:"+field.name,field);if(field.valid){this.checkValid()}else{this.setValid(false)}},remove:function(){this.el.removeEventListener("submit",this.handleSubmit,false);var parent=this.el.parentNode;if(parent)parent.removeChild(this.el);this._fieldViewsArray.forEach(function(field){field.remove()})},handleSubmit:function(e){this.beforeSubmit();this.checkValid();if(!this.valid){e.preventDefault();return false}if(this.preventDefault){e.preventDefault();this.submitCallback(this.getData());return false}},getData:function(){var res={};for(var key in this._fieldViews){res[key]=this._fieldViews[key].value}return this.clean(res)},render:function(){if(this.rendered)return;if(!this.el){this.el=document.createElement("form")}if(this.autoAppend){this.fieldContainerEl=this.el.querySelector("[data-hook~=field-container]")||this.el}this.handleSubmit=this.handleSubmit.bind(this);this.el.addEventListener("submit",this.handleSubmit,false);this.rendered=true}});FormView.extend=function(obj){var child=function(){FormView.apply(this,arguments)};extend(child.prototype,FormView.prototype);extend(child.prototype,obj);return child};module.exports=FormView},{"backbone-events-standalone":2,"extend-object":3}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){if(typeof window!=="undefined"){window.ampersand=window.ampersand||{};window.ampersand["ampersand-dom"]=window.ampersand["ampersand-dom"]||[];window.ampersand["ampersand-dom"].push("1.2.7")}var dom=module.exports={text:function(el,val){el.textContent=getString(val)},addClass:function(el,cls){cls=getString(cls);if(!cls)return;if(Array.isArray(cls)){cls.forEach(function(c){dom.addClass(el,c)})}else if(el.classList){el.classList.add(cls)}else{if(!hasClass(el,cls)){if(el.classList){el.classList.add(cls)}else{el.className+=" "+cls}}}},removeClass:function(el,cls){if(Array.isArray(cls)){cls.forEach(function(c){dom.removeClass(el,c)})}else if(el.classList){cls=getString(cls);if(cls)el.classList.remove(cls)}else{el.className=el.className.replace(new RegExp("(^|\\b)"+cls.split(" ").join("|")+"(\\b|$)","gi")," ")}},hasClass:hasClass,switchClass:function(el,prevCls,newCls){if(prevCls)this.removeClass(el,prevCls);this.addClass(el,newCls)},addAttribute:function(el,attr){el.setAttribute(attr,"");if(hasBooleanProperty(el,attr))el[attr]=true},removeAttribute:function(el,attr){el.removeAttribute(attr);if(hasBooleanProperty(el,attr))el[attr]=false},setAttribute:function(el,attr,value){el.setAttribute(attr,getString(value))},getAttribute:function(el,attr){return el.getAttribute(attr)},hide:function(el){if(!isHidden(el)){storeDisplayStyle(el);hide(el)}},show:function(el){show(el)},html:function(el,content){el.innerHTML=content}};function getString(val){if(!val&&val!==0){return""}else{return val}}function hasClass(el,cls){if(el.classList){return el.classList.contains(cls)}else{return new RegExp("(^| )"+cls+"( |$)","gi").test(el.className)}}function hasBooleanProperty(el,prop){var val=el[prop];return prop in el&&(val===true||val===false)}function isHidden(el){return dom.getAttribute(el,"data-anddom-hidden")==="true"}function storeDisplayStyle(el){dom.setAttribute(el,"data-anddom-display",el.style.display)}function show(el){el.style.display=dom.getAttribute(el,"data-anddom-display")||"";dom.removeAttribute(el,"data-anddom-hidden")}function hide(el){dom.setAttribute(el,"data-anddom-hidden","true");el.style.display="none"}},{}],2:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],3:[function(require,module,exports){"use strict";var proto=Element.prototype;var vendor=proto.matches||proto.matchesSelector||proto.webkitMatchesSelector||proto.mozMatchesSelector||proto.msMatchesSelector||proto.oMatchesSelector;module.exports=match;function match(el,selector){if(vendor)return vendor.call(el,selector);var nodes=el.parentNode.querySelectorAll(selector);for(var i=0;i<nodes.length;i++){if(nodes[i]==el)return true}return false}},{}],"ampersand-select-view":[function(require,module,exports){if(typeof window!=="undefined"){window.ampersand=window.ampersand||{};window.ampersand["ampersand-select-view"]=window.ampersand["ampersand-select-view"]||[];window.ampersand["ampersand-select-view"].push("2.4.0")}var domify=require("domify");var dom=require("ampersand-dom");var matches=require("matches-selector");var defaultTemplate=['<label class="select">','<span data-hook="label"></span>',"<select></select>",'<span data-hook="message-container" class="message message-below message-error">','<p data-hook="message-text"></p>',"</span>","</label>"].join("\n");function SelectView(opts){opts=opts||{};if(typeof opts.name!=="string")throw new Error("SelectView requires a name property.");this.name=opts.name;if(!Array.isArray(opts.options)&&!opts.options.isCollection){throw new Error("SelectView requires select options.")}this.options=opts.options;if(this.options.isCollection){this.idAttribute=opts.idAttribute||this.options.mainIndex||"id";this.textAttribute=opts.textAttribute||"text";this.disabledAttribute=opts.disabledAttribute}this.el=opts.el;this.value=null;this.label=opts.label||this.name;this.parent=opts.parent;this.template=opts.template||defaultTemplate;this.unselectedText=opts.unselectedText;this.yieldModel=opts.yieldModel===false?false:true;this.required=opts.required||false;this.validClass=opts.validClass||"input-valid";this.invalidClass=opts.invalidClass||"input-invalid";this.requiredMessage=opts.requiredMessage||"Selection required";this.onChange=this.onChange.bind(this);this.render();this.setValue(opts.value)}SelectView.prototype.render=function(){if(this.rendered)return;if(!this.el)this.el=domify(this.template);var label=this.el.querySelector("[data-hook~=label]");if(label){label.textContent=this.label}this.select=this.el.querySelector("select");if(matches(this.el,"select"))this.select=this.el;if(this.select)this.select.setAttribute("name",this.name);this.bindDOMEvents();this.renderOptions();this.updateSelectedOption();if(this.options.isCollection){this.options.on("add remove reset",function(){this.renderOptions();this.updateSelectedOption()}.bind(this))}this.rendered=true};SelectView.prototype.onChange=function(){var value=this.select.options[this.select.selectedIndex].value;if(this.options.isCollection&&this.yieldModel){value=this.findModelForId(value)}this.setValue(value)};SelectView.prototype.findModelForId=function(id){return this.options.filter(function(model){if(!model[this.idAttribute])return false;return model[this.idAttribute]==id}.bind(this))[0]};SelectView.prototype.bindDOMEvents=function(){this.el.addEventListener("change",this.onChange,false)};SelectView.prototype.renderOptions=function(){if(!this.select)return;this.select.innerHTML="";if(this.unselectedText){this.select.appendChild(createOption(null,this.unselectedText))}this.options.forEach(function(option){this.select.appendChild(createOption(this.getOptionValue(option),this.getOptionText(option),this.getOptionDisabled(option)))}.bind(this))};SelectView.prototype.updateSelectedOption=function(){var lookupValue=this.value;if(!this.select)return;if(!lookupValue){this.select.selectedIndex=0;return}if(this.options.isCollection&&this.yieldModel){lookupValue=lookupValue&&lookupValue[this.idAttribute]}if(lookupValue){for(var i=this.select.options.length;i--;i){if(this.select.options[i].value===lookupValue.toString()){this.select.selectedIndex=i;return}}}this.select.selectedIndex=0};SelectView.prototype.remove=function(){if(this.el)this.el.parentNode.removeChild(this.el);this.el.removeEventListener("change",this.onChange,false)};SelectView.prototype.clear=function(){this.setValue("",true)};SelectView.prototype.setValue=function(value,skipValidation){if(value===this.value)return;if(this.options.isCollection){var model;if(this.options.indexOf(value)===-1){model=this.findModelForId(value)}else{model=value}if(this.yieldModel){value=model}else{if(model){value=model[this.idAttribute]}else{value=void 0}}}this.value=value;if(!skipValidation)this.validate();this.updateSelectedOption();if(this.parent)this.parent.update(this)};SelectView.prototype.validate=function(){if(!this.value&&!this.required){this.valid=true}else{this.valid=this.options.some(function(element){if(this.options.isCollection){if(this.yieldModel){return this.options.indexOf(this.value)>-1}else{return!!this.findModelForId(this.value)}}if(Array.isArray(element)&&element.length===2){return element[0]===this.value}return element===this.value}.bind(this))}if(!this.valid&&this.required){this.setMessage(this.requiredMessage)}else{this.setMessage()}return this.valid};SelectView.prototype.getOptionValue=function(option){if(Array.isArray(option))return option[0];if(this.options.isCollection){if(this.idAttribute&&option[this.idAttribute]){return option[this.idAttribute]}}return option};SelectView.prototype.getOptionText=function(option){if(Array.isArray(option))return option[1];if(this.options.isCollection){if(this.textAttribute&&option[this.textAttribute]){return option[this.textAttribute]}}return option};SelectView.prototype.getOptionDisabled=function(option){if(Array.isArray(option))return option[2];if(this.options.isCollection&&this.disabledAttribute)return option[this.disabledAttribute];return option};SelectView.prototype.setMessage=function(message){var mContainer=this.el.querySelector("[data-hook~=message-container]");var mText=this.el.querySelector("[data-hook~=message-text]");if(!mContainer||!mText)return;if(message){dom.show(mContainer);mText.textContent=message;dom.addClass(this.el,this.invalidClass);dom.removeClass(this.el,this.validClass)}else{dom.hide(mContainer);mText.textContent="";dom.addClass(this.el,this.validClass);dom.removeClass(this.el,this.invalidClass)}};function createOption(value,text,disabled){var node=document.createElement("option");if(value===null||value===undefined){value=""}if(disabled)node.disabled=true;node.textContent=text;node.value=value;return node}module.exports=SelectView},{"ampersand-dom":1,domify:2,"matches-selector":3}]},{},[]);var FormView=require("ampersand-form-view");var SelectView=require("ampersand-select-view");var MyForm=FormView.extend({validCallback:function(valid){if(valid){console.log("The form is valid!")}else{console.log("The form is not valid!")}},fields:[new SelectView({autoRender:true,label:"test1",name:"test2",value:"SOME INITIAL VALUE...",options:["blue","orange","red"],tests:[],unselectedText:"Add canned response",required:false})]});var myForm=new MyForm;document.body.appendChild(myForm.el);
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"ampersand-form-view": "2.2.0",
"ampersand-select-view": "2.4.0"
}
}
<style type='text/css'>html, body { margin: 0; padding: 0; border: 0; }
body, html { height: 100%; width: 100%; }</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment