/* Copyright (c) 2007 Pelle Braendgaard (pelle@stakeventures.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* ============ DOM-RESOURCE ============ $LastChangedDate$ $Rev$ $Author$ This is a simple rest based AJAX API with a very DRY (Don't Repeat Yourself) approach. It is inspired heavily by ActiveRecord/ActiveResource and is designed to work well in a Rails environment, eventhough you could easily use it with PHP, Java or whatever. The code is available at http://code.google.com/p/dom-resource/ I blog primarily on http://stakeventures.com DEPENDENCIES dom-resource relies on 2 existing libraries: - Prototype which is avilable at http://prototypejs.org - Ryan Schuft's inflection.js at http://code.google.com/p/inflection-js/ QUICK START You map an object to a resource by following standard rails conventions in naming your elements dom id's. EG:
Pelle
Bob
I will delete you
Here you can either work with the collection as a whole using the $RES(plural_id) function: $RES('people') => DOM element extended with special resource methods below $RES('people').count() => 3 $RES('people').reload() => AJAX GET call to /people $RES('people').create({name:'Dwight',email:'dwight@dundermifflin.com'}) => AJAX POST call to /people $RES('people').find(2) =>
[array of all person elements] or individual objects using $REC(singular_id) function: $REC('person_1') => DOM element extended with special resource methods below $REC('person_1').db_id() => 1 $REC('person_1').get('name') => 'Pelle' $REC('person_1').resource() => $RES('people') $REC('person_1').destroy() => AJAX delete to /people/1 then removes from dom $REC('person_1').action('toggle') => AJAX post to /people/1;toggle then replaces element with result You can extend your objects yourself by creating a module definition: var Person={ initialize:function(){ this.name=this.getName(); this.email=this.getEmail(); }, getName:function(){ return this.get('name'); }, getEmail:function(){ return this.get('email'); } } $REC() automatically deduces the class name (Singular Capitalized) and checks if it exists. If it does it extends the element with these methods and calls the initialize method without parameters. This is work in progress so please bear with me on any errors. */ if (!window.Resource) var Resource={}; Resource.highlight=function(element){ new Effect.Highlight(element); }; Resource.remove=function(element){ new Effect.Fade(element); }; Resource.error=function(request){ $('notice').addClassName('error'); $('notice').update(request.responseText); new Effect.Shake('notice'); }; Resource.flash=function(request){ $('notice').removeClassName('error'); $('notice').update(request.responseText); }; Resource.methods={ count: function(){ return this.all().length; }, all: function(){ return this.getElementsByClassName(this.instance_name); }, find: function(id){ return $REC(this.instance_name+'_'+id); }, url: function(){ if (!this._url) this._url=this.resource_prefix+'/'+this.collection_name; return this._url; }, reload: function(options){ var options=options||{}; options.method='get'; new Ajax.Updater(this,this.url(),options); }, create: function(data){ new Ajax.Updater({success:this,failure:'notice'},this.url(),{method:'post',parameters:this.toQueryString(data),insertion:Insertion.Bottom,onFailure:Resource.error}); }, createFromForm: function(form){ var formElement=$(form); new Ajax.Updater(this,this.url(),{method:'post',parameters:formElement.serialize(),insertion:Insertion.Bottom,onFailure:Resource.error}); }, toQueryString: function(params){ var parts = new Array(params.length); for (part in params) parts.push(this.instance_name+'['+part+']='+params[part]); return parts.join('&'); } }; Resource.extend = function(obj) { var element; var resource_prefix=''; if (typeof(obj)=='string'){ var pos=obj.lastIndexOf('/'); if (pos>=0){ resource_prefix=Resource.stripHttpAndHost(obj.substring(0,pos)); // name=obj.substring(pos+1); name=Resource.toId(Resource.stripHttpAndHost(obj)); } else { name=obj; } element=Resource.findCollection(name); if (element.tagName=='FORM') return $RES(Resource.stripHttpAndHost(element.action)); } else element=obj; if (!element || !element.tagName || element.nodeType == 3 || element == window || element.collection_name) return element; element.resource_prefix=resource_prefix; name.match(/(\d+_)?([a-z_]+$)/); name=RegExp.$2; element.collection_name=name; element.instance_name=name.singularize(); for (var property in Resource.methods) { var value = Resource.methods[property]; if (typeof value == 'function' && !(property in element)) element[property] = value; } return element; }; function $RES(obj){ return Resource.extend(obj); }; Resource.toPath=function(name){ return '/'+name.gsub(/([a-z]+)_(\d+)(_?)/,function(match){ return match[1].pluralize()+'/'+match[2]+(match[3]=='_' ? '/':''); }); }; Resource.findCollection=function(name){ var element=$(name); if (element!=null) return element; if (name.match(/[a-z]+_\d+_(.+)/)) return Resource.findCollection(RegExp.$1); return null; }; Resource.stripHttpAndHost=function(url){ if (url.match(/^(https?:\/\/\w+(\.\w+)*(:\d+)?)/)) url=url.substring(RegExp.$1.length); return url; }; Resource.toId=function(path){ return Resource.stripHttpAndHost(path).substring(1).gsub(/([a-z]+)\/(\d+)/,function(match){ return match[1].singularize()+'_'+match[2]; }).gsub(/\//,'_'); }; Resource.isResourceId=function(name){ return (/(\w+)(_(\d+))$/.test(name)); }; if (!window.Resource.Record) Resource.Record={}; // Helper function to extract the value of an element. Support for microformats will be added here. Resource.valueOf=function(element){ if (element==null) return null; if (element.nodeName=='ABBR'&&element.getAttribute('title')!=null) return element.getAttribute('title'); else return element.textContent; }; Resource.Record.methods={ get: function(name){ return Resource.valueOf(this.getElement(name)); }, getElement: function(name){ var children=this.getElementsByClassName(name); if (children.length==0) return null; else return children[0]; }, set: function(name,value){ var children=this.getElementsByClassName(name); if (children.length>0) children[0].update(value); }, update_attribute: function(name,value){ this.set(name,value); this.save(); }, db_id: function(){ return parseInt(this.id.match(/[a-z]+_(\d+)$/)[1],10); }, instance_name: function(){ return this.id.match(/([a-z]+)_\d+$/)[1]; }, collection_name: function(){ return this.instance_name().pluralize(); }, module_name: function(){ return this.instance_name().capitalize(); }, resource: function(){ if (this._resource==null) this._resource=$RES(this.collection_name); return this._resource; }, url: function(){ return Resource.toPath(this.id); }, toHash: function(){ var params=new Hash(); var children=this.descendants(); for (i in children){ var attr=children[i]; if (attr.className) {// Make bad assumpution that we are only interested in the first class params[attr.className]=Resource.valueOf(attr); } } return params; }, toQueryString: function(){ return this.toHash().toQueryString(); //Todo fill this one out }, action: function(action,params){ var saveEvent=this.onSave.bind(this); new Ajax.Request( this.url()+';'+action, {method: 'post', parameters:(params ? params.toQueryString() :''),onSuccess:saveEvent,onFailure:Resource.error}); }, save: function(form){ var params=(form!=null)?form.serialize():this.toQueryString(); var saveEvent=this.onSave.bind(this); new Ajax.Request( this.url(), {method: 'put', parameters:this.toQueryString(),onSuccess:saveEvent,onFailure:Resource.error}); }, destroy: function(){ var destroyEvent=this.onDestroy.bind(this); if (confirm("Are you sure?")) new Ajax.Request( this.url(), {method: 'delete',onSuccess:destroyEvent,onFailure:Resource.error}); }, onSave: function(request){ this.replace(request.responseText); }, onDestroy: function(request){ this.remove(); } }; Resource.Record.extend = function(obj) { var element; if (typeof(obj)=='string'){ element=$(obj); } else element=obj; if (!element || !element.tagName || element.nodeType == 3 || element == window || element.collection) return element; for (var property in Resource.Record.methods) { var value = Resource.Record.methods[property]; if (typeof value == 'function' && !(property in element)) element[property] = value; } try { var mixin=window[element.module_name()]; if (mixin){ Object.extend(element,mixin); } if (element.initialize) element.initialize(); } catch(e){}; // I'm making a very bold assumption that the mixin does not exist here return element; }; function $REC(obj){ return Resource.Record.extend(obj); };