
QCObjects
Welcome to QCObjects Main Reference Documentation!
Check the official page of QCObjects at https://qcobjects.dev
Cross Browser Javascript Framework for MVC Patterns
QCObjects is a javascript framework designed to make easier everything about the MVC patterns implementation into the pure javascript scope. You don't need to use typescript nor any transpiler to run QCObjects. It runs directly on the browser and it uses pure javascript with no extra dependencies of code. You can make your own components expressed in real native javascript objects or extend a native DOM object to use in your own way. You can also use QCObjects in conjunction with CSS3 frameworks like [Foundation] (https://foundation.zurb.com), [Bootstrap] (http://getbootstrap.com) and mobile javascript frameworks like [PhoneGap] (https://phonegap.com) and OnsenUI (https://onsen.io)

Table of Contents
ALPHA RISE Startup

QCObjects was invited to exhibit as an ALPHA Startup in the RISE Conf Hong Kong 2019. RISE attracts the most dynamic startups from around the world. We'll be showing how QCObjects is making a real Global Impact to the JavaScript developers life transforming the way for coding.
If you want to find out more about RISE event check out their website https://riseconf.com
ECMA-262 Specification
See
ECMAScript® 2020 Language Specification for reference
Copyright
Copyright (c) Jean Machuca and QuickCorp info@quickcorp.cl
Demo
Demo Using Foundation
Check out a demo using Foundation components here:
Demo Using Foundation
Demo Using Materializecss
Check out a demo using MaterializeCSS here:
Demo Using Materializecss
Demo Using Raw CSS
Check out a demo using raw CSS:
Demo Using Raw CSS
Another Basic Demo example: The simpliest demo example:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script type="text/javascript" src="https://qcobjects.dev/QCObjects.js"></script>
<script type="text/javascript">
var canvas1,canvas2,canvas3,container;
CONFIG.set('relativeImportPath','src/');
Import('cl.quickcorp',function (){
Class('MyOwnBody',HTMLBodyElement,{
customAttr:'custom',
body:document.body
});
Class('MyContainer',HTMLElement,{
width:400,
height:400,
customAttr:'custom attr container'
});
Class('canvas',HTMLCanvasElement,{
customAttr:'custom'
});
Class('MyCanvas2',HTMLCanvasElement,{});
body = New(MyOwnBody);
body.css({backgroundColor:'#ccc'});
container = document.getElementsByTagName('container')[0].Cast(MyContainer);
container.css({backgroundColor:'red'});
canvas1 = New(canvas,{
width:100,
height:100,
});
canvas2 = New(canvas,{
width:200,
height:100,
});
canvas3 = New(canvas,{
width:300,
height:50,
});
canvas1.css({backgroundColor:'#000000'});
canvas1.body.style.backgroundColor='#000000';
canvas2.body.style.backgroundColor='#0044AA';
canvas3.body.style.backgroundColor='green';
canvas1.append();
canvas2.attachIn('container');
container.append(canvas3);
body.append(canvas3);
var c1 = New(Component,{'templateURI':'templatesample.html',cached:false});
document.body.append(c1);
});
</script>
</head>
<body>
<container id="contentLoader" ></container>
</body>
</html>
Fork
Please fork this project or make a link to this project into your README.md file. Read the LICENSE.txt file before you use this code.
If you want to become a sponsor for this wonderful project you can do it here
Check out the QCObjects SDK
You can check out the QCObjects SDK and follow the examples to make your own featured components
Donate
If you like this code please DONATE!

Installing
Using QCObjects with Atom:
> apm install qcobjects-syntax
https://atom.io/packages/qcobjects-syntax
Using QCObjects in Visual Studio Code:
https://marketplace.visualstudio.com/items?itemName=Quickcorp.QCObjects-vscode
Installing with NPM:
> npm install qcobjects
Using the code in the straight way into HTML5:
<script type="text/javascript" src="https://qcobjects.dev/QCObjects.js"></script>
Reference
Essentials
Here are the essentials symbols and concepts of QCObjects Reference
QC_Object
Basic Type of all elements
ComplexStorageCache
With CompletStorageCache you can handle a cache for any object and save it in the local storage.
Usage:
var cache = new CompletStorageCache({
index:object.id,
load:(cacheController)=>{},
alternate: (cacheController)=>{}
});
Example:
var dataObject = {id:1,
prop1:1,
prop2:2
};
var cache = new ComplexStorageCache({
index: dataObject.id,
load: (cacheController) => {
dataObject = {
id:dataObject.id,
prop1:dataObject.prop1*2,
prop2:dataObject.prop2
};
return dataObject;
},
alternate: (cacheController) => {
dataObject = cacheController.cache.getCached(dataObject.id);
return;
}
});
var dataObjectCopyFromCache = cache.getCached(dataObject.id);
console.log(dataObjectCopyFromCache);
asyncLoad
The asyncLoad function loads a code once in async mode. This is useful to asure some initial process don't replicate its execution and aren't loaded after sensitive code.
Usage:
asyncLoad(()=>{
},args);
Example:
let doSomething = (arg1,arg2)=>{
asyncLoad((arg1,arg2)=>{
console.log(arg1);
console.log(arg2);
},arguments);
};
doSomething(1,2);
Class
This is NOT the class definition of ECMAScript 2015 (see class ECMAScript 2015 for reference).
Class is a special function to help you to declare a class in an easier and compatible way. It works cross-browser, and I hope ECMA could adopt something like that in the future. To let javascript not to be confuse about this, QCObjects uses "Class" not "class" (note the Camel Case).
Usage:
Class('MyClassName',MyClassDefinition);
Where MyClassDefinition is an object with a QCObjects prototype
Example:
Class('MyClassName',InheritClass,{
propertyName1:0,
propertyName2:'',
classMethod1: function (){
return this.propertyName1;
},
classMethod2: function () {
return this.propertyName2;
}
});
var newObject = New(MyClassName,{
propertyName1:1,
propertyName2:"some value"
});
console.log(newObject.classMethod1());
console.log(newObject.classMethod2());
QC_Append, append method
This is a special method inserted to make your life easier when you want to dynamically manipulate the DOM. You can insert even a Component, a QCObjects Object or a DOM Element inside another HTMLElement.
Usage:
[element].append([object or element]);
Example:
Class('canvas',HTMLCanvasElement,{
customAttr:'custom'
});
let canvas1 = New(canvas,{
width:100,
height:100,
});
document.body.append(canvas1);
The _super_ method
When you extend a QCObjects class from another one, you can use _super_ method to get an instance from the main class definition.
Usage:
_super_('MySuperClass','MySuperMethod').call(this,params)
Example:
Class('MySuperiorClass',InheritClass,{
propertyName1:0,
propertyName2:'',
classMethod1: function (){
return this.propertyName1;
},
});
Class('MyClassName',MySuperiorClass,{
propertyName1:0,
propertyName2:'',
classMethod2: function () {
return _super_('MySuperiorClass','classMethod1').call(this);
}
});
var newObject = New(MyClassName,{
propertyName1:1,
propertyName2:"some value"
});
console.log(newObject.classMethod2());
New
Creates an object instance of a QCObjects class definition.
Usage:
let objectInstance = New(QCObjectsClassName, properties);
NOTE: In the properties object you can use single values or getter as well but they will be executed once.
Example:
Class('MyCustomClass',Object);
let objectInstance = New(MyCustomClass,{
prop1:1,
get randomNumber(){
return Math.random();
}
});
console.log(objectInstance.randomNumber);
InheritClass
A single common used QCObjects class definition.
_Crypt
With _Crypt you can encode serializable objects by a passphrase
Example (1):
var _string = New(_Crypt,{string:'hello world',key:'some encryption md5 key'});
console.log(_string._encrypt());
console.log(_string._decrypt());
Example (2):
_Crypt.encrypt('hola mundo','12345678866');
_Crypt.decrypt('nqCelFSiq6Wcpw==','12345678866');
GLOBAL
GLOBAL is a special QCObjects class to reach the global scope. It has a set and a get method to help you to manage the internal GLOBAL properties.
Example:
GLOBAL.set('globalProperty1','some value in global scope');
var globalProperty1 = GLOBAL.get('globalProperty1');
CONFIG
CONFIG is a smart class that manages the global settings of your application. You can get the properties either from a config.json or from the memory previously saved by a set() call.
Usage from memory:
1.- In your initial code set the CONFIG initial values:
CONFIG.set('someSettingProperty','some initial value');
2.- Then you can access it from anywhere in your code by using the get method:
var someSettingProperty = CONFIG.get('someSettingProperty');
Usage from config.json:
1.- You need to indicate first that you are using a config.json file by setting the "useConfigService" value to true
CONFIG.set('useConfigService',true);
2.- Once you have set the value above QCObjects will know and look to the next CONFIG settings into the file config.json in the basePath folder of your application.
Usage from an encrypted config.json:
There is also a way to use an encrypted config.json file in order to protect your settings robots that can steal unprotected data from your web application (like API keys web crawlers).
To encrypt your json file go to https://config.qcobjects.dev, put your domain and the config.json content. The tool will encrypt your json and you can copy the encrypted content to insert it in your config.json file. QCObjects will know the data is encrypted and the process to decode the data will be transparent for you.
waitUntil
waitUntil is a helper just in case you are in trouble trying to run a code before a condition is true. The code inside waitUntil will be executed once.
NOTE: This is useful in some cases but an excessive use is not recommended.
Usage:
waitUntil(()=>{
},()=>{return condition;});
Example:
let someVar = 0;
waitUntil(()=>{
console.log('someVar is present');
},()=>{return typeof someVar != 'undefined';});
Package
Defines a QCObjects package and returns it.
Usage:
Package('packageName',[packageContent]);
Where packageContent is an array of QCObjects Classes. If you only pass the packageName param you will get the previously declared package content.
Example (1):
'use strict';
Package('org.quickcorp.main',[
Class('Main',InheritClass,{
propertyName1:'propertyValue1',
}),
Class('MyCustomClass',InheritClass,{
propertyName2:'propertyValue2',
}),
]);
Example (2):
let mainPackage = Package('org.quickcorp.main');
Import
Imports a package from another JS file
Usage:
Import (packagename,[ready],[external]);
Where packagename is the name of the package, ready is a function that will be executed after the package is loaded, and external is a boolean value that indicates if the JS file is in the same origin or it is from another external resource.
Example (1):
Import('org.quickcorp.main');
The above code will try to import a JS fila named 'org.quickcorp.main.js' from the path specified in the relativeImportPath settings value present in your CONFIG. Inside the JS file you have to define a package by using Package('org.quickcorp.main',[Class1, Class2...])
Example (2):
Import('org.quickcorp.main',function (){
console.log('remote import is loaded');
},true);
The above code this time is trying to load the same package but using an external path defined by the remoteImportsPath setting present in your CONFIG
NOTE: In both examples above you have not use or specify the ".js" extension. This it's used by default and can't be changed by security reasons.
Export
Put a symbol (var or function) in the global scope.
Usage:
Export('name of symbol');
Example:
(()=>{
let someFunction = (someLocalParam)=>{
console.log(someLocalParam);
};
Export(someFunction);
})();
someFunction('this works');
Cast
Use the Cast method of any DOM element to get the properties of another type of object. This is useful to transform an object type to another giving more flexibility in your code.
Usage:
let resultObject = [element or QCObjects type].Cast(objectToCastFrom);
Where objectToCastFrom is an object to get the properties from and put it into the result object returned by Cast.
Example:
Class('MyOwnClass',{
prop1:'1',
prop2:2
});
let obj = document.createElement('div').Cast(MyOwnClass);
The above code will create a DOM object and Cast it to MyOwnClass. Because of MyOwnClass is a QCObjects type class, obj will now have a prop1 and prop2 properties, and will now be a QCObjects object instance with a body property that is a div element.
Tag
Tag is a useful function to select any DOM element using selectors. Tag will always return a list of elements, that you can map, sort, and filter as any other list.
Usage:
var listOfElements = Tag(selector);
Where selector is a DOM query selector.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script type="text/javascript" src="https://qcobjects.dev/QCObjects.js"></script>
</head>
<body>
<div class="myselector">
<p>Hello world</p>
</div>
<script>
Ready(()=>{
Tag('.myselector > p').map((element)=>{
element.innerHTML = 'Hello world! How are you?';
});
});
</script>
</body>
</html>
In the above code, a paragraph element was created inside a div with a css class named myselector by html, and then is modified dynamically using the QCObjects Tag function. If you are familiar with query selector frameworks like JQuery, you will love this one.
Ready
Assign a function to run after everything is done by QCObjects and after the window.onload event. Use it to prevent 'undefined' DOM objects error.
Usage:
Ready(()=>{
});
Note that if you define dynamic components by using a HTML "component" tag, the dynamic content load will not trigger Ready events. To catch code everytime a dynamic component is loaded, use a Controller done method instead.
You will use Ready implementation mostly when you want to implement QCObjects in conjunction with another framework that needs it.
Component Class
A QCObjects class type for components.
Properties
[Component].domain
Returns a string with the domain of your application. It is automatically set by QCObjects at the load time.
[Component].basePath
Returns a string with the base path url of your application. It is automatically set by QCObjects at the load time.
NOTE: If you want to change the components base path, you have to use CONFIG.set('componentsBasePath','new path relative to the domain') in your init code.
[Component].templateURI
Is a string representing the component template URI relative to the domain. When is set, the component will load a template and append the inner content into the body childs as a part of the DOM. To set this property, it is recommended to use the ComponentURI helper function.
[Component].tplsource
Is a string representing the source where the template will be loaded. It can be "default" or "none". A value of "default" will tell QCObjects to load the template from the templateURI content. A value of "none" will tell QCObjects not to load a template from anywhere.
[Component].url
Is a string representing the entire url of the component. It is automatically set by QCObjects when the component is instantiated.
[Component].name
Is a string representing the name of a component. The name of a component can be any alphanumeric value that identifies the component type. It will be internally used by ComponentURI to build a normalised component template URI.
[Component].method
Is a string representing a HTTP or HTTPS method. By default, every component is set to use the "GET" method. In the most of cases, you don't need to change this property.
[Component].data
Is an object representing the data of the component. When QCObjects loads a template, it will get every property of data object and bind it to a template label representing the same property inside the template content between double brakets (example: {{prop1}} in the template content will represent data.prop1 in the component instance).
NOTE: To refresh the data bindings it is needed to rebuild the component (see the use of [Component].rebuild() method for more details ).
[Component].reload
Is a boolean value that tells QCObjects when to force reload the content of a component from the template or not. If its value is true, the template content will be replacing the current DOM childs of the component body element. If its value is false, the template content will be added after the las component body child.
[Component].cached
Is a boolean value that tells QCObjects if the component needs to be cached or not. When a component is cached, the template content loaded from templateURI will be loaded once. You can set this property either as a static property of the Component Class to set the default value for every next component object instance, or setting the individual value of the property in every component definition. In a world where the performance matters, to give more flexibility to the cache behaviour is needed more than ever.
[Component].routingWay
Returns a string representing the routing way. Its value can be "hash", "pathname" or "search".
NOTE: To change the routingWay of every component it is recommended to use CONFIG.set('routingWay','value of a valid routing way') in your init code.
[Component].validRoutingWays
Returns a list representing the valid routing ways. QCObjects uses this to internally validate the routingWay which was used to build the component routings.
[Component].routingNodes
Returns a NodeList object representing the list of nodes that were loaded by the component routing builder.
[Component].routings
Returns a list with the component routings built when the component was instantiated.
[Component].routingPath
Returns a string representing the current routing path
[Component].routingSelected
Returns an object representing the current routing of the component
[Component].subcomponents
Returns a list of components that are childs of the component instance.
[Component].body
Is a DOM element representing the body of the component.
NOTE: Every time a component body is set, it will trigger the routings builder for this component.
Methods
[Component].set('prop',value)
Sets a value for a component property.
[Component].get('prop')
Returns the value of a component property
[Component].rebuild()
Rebuilds the component. It will force a call for the componentLoader with this component when it's needed.
[Component].Cast(ClassName or ComponentClassName)
Returns the cast of a component definition into another one. This is useful to dynamically merge components definitions.
[Component].route()
Forces the component routings builder to reload the routings of the component. This will result in a rebuild call when it's needed.
[Component].fullscreen()
Puts the component in fullscreen mode.
[Component].closefullscreen()
Closes the fullscreen mode.
[Component].css(css object)
Sets the css properties for the component.
[Component].append(component or QCObjects object)
Appends a component as a child of the current component body
[Component].attachIn(selector)
Attaches a current component body to any element in the given selector.
Component HTML Tag
Is a HTML tag representation of a component instance. Every declaration of a <component></component>
tag will generate a related instance of a QCObjects component. While a component tag is not an instance itself, you can even define some instance properties by setting the related tag attribute when it is available.
Available attributes
Below is a list of the available attributes for a component tag
The name Attribute
<component name>
Sets the name of the related component instance built by QCObjects.
Usage:
<component name="name_of_component"></component>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script type="text/javascript" src="https://qcobjects.dev/QCObjects.js"></script>
</head>
<body>
<component name="main"></component>
</body>
</html>
The cached Attribute
<component cached>
Sets the cached property if the related instance of a component.
NOTE: Only a value of "true" can be set in order to tell QCObjects that the component template content has to be cached. Any other value will be interpreted as false.
Usage:
<component name="name_of_component" cached="true"></component>
The data property tag declaration
<component data-property1 data-property2 ...>
Sets a static value of a property for the data object in the component instance.
NOTE: Data property tag declaration was thought with the purpose to give some simple way to mocking a dynamic component with template assignments. Don't use it thinking it is a bidirectional way data binding. While you can get a bidirectional way behaviour accesing a data object from a component instance, it is not the same for the component tag. Data property declaration in component tags is only one way data binding because of components tree architecture.
The controllerClass Attribute
<component controllerClass>
Defines a custom Controller Class for the component instance
Usage:
<component name="name_of_component" controllerClass="ControllerClassName"></component>
The viewClass Attribute
<component viewClass>
Defines a custom View Class for the component instance
Usage:
<component name="name_of_component" viewClass="ViewClassName"></component>
The componentClass Attribute
<component componentClass>
Defines a custom Component Class for the component instance
Usage:
<component name="name_of_component" componentClass="ComponentClassName"></component>
The effecClass Attribute
<component effectClass>
Defines a custom Effect Class for the component instance
Usage:
<component name="name_of_component" effectClass="EffectClassName"></component>
The template-source Attribute
<component template-source>
Sets the tplsource property of the related instance of a component. Possible values are "none" or "default".
Usage:
<component name="name_of_component" template-source="none"></component>
The tplextension Attribute
<component tplextension>
Sets the tplextension property of the related instance of a component. Possible values are any file extension. Default value is "html"
Usage:
<component name="name_of_component" tplextension="tpl.html"></component>
ComponentURI
Is a helper function to let you define the templateURI for a component in a normalised way.
Example:
var templateURI = ComponentURI({
'COMPONENTS_BASE_PATH':CONFIG.get('componentsBasePath'),
'COMPONENT_NAME':'main',
'TPLEXTENSION':"tpl.html",
'TPL_SOURCE':"default"
});
console.log(templateURI);
componentLoader
Loads a component instance in a low level, and appends the component template content to the component body. In the most of cases you won't need to call componentLoader in order to load a component. This is automatically called by QCObjects when it's needed. componentLoader returns a promise that is resolved when the component load is done and rejected when the component load was failed.
Usage:
[Promise] componentLoader(componentInstance,load_async)
Where componentInstance is a component instance created by New(ComponentDefinitionClass)
Example:
componentLoader(componentInstance,load_async).then(
(successStandardResponse)=>{
var request = successStandardResponse.request;
var component = successStandardResponse.component;
},(failStandardResponse)=>{
var component = failStandardResponse.component;
});
buildComponents
Rebuilds every component that is a child element of the DOM element who owns the method. In the most of cases, you won't need to call buildComponents in order to build or rebuild every component in the DOM. This is automatically called by QCObjects when it's needed.
Usage:
[element].buildComponents()
Example:
document.buildComponents()
Controller
A built-in QCObjects Class to define a controller
View
A built-in QCObjects View to define a view
VO
A built-in QCObjects Class to define a value object
Service
A QCObjects class type for services.
Properties
[Service].domain
Returns a string with the domain of your application. It is automatically set by QCObjects at the load time.
[Service].basePath
Returns a string with the base path url of your application. It is automatically set by QCObjects at the load time.
[Service].url
Is a string representing the entire url of the service. It can be absolute or relative to the basePath when it applies. It can be also an external url.
NOTE: To load a service of an external resource you need to specify the external parameter to true using serviceLoader.
[Service].name
Is a string representing the name of a component. The name of a service can be any alphanumeric value that identifies the service instance. It isn't a unique ID but only a descriptive name.
[Service].method
Is a string representing a HTTP or HTTPS method. Possible values are: "GET", "POST", "PUT", ... any other that is accepted by REST services calls.
[Service].data
Is an object representing the data of the service. When QCObjects loads a service. It receives the response and interpretes it as a template. So once a service response is obtained, it will get every property of data object and bind it to a template label representing the same property inside the template content between double brakets (example: {{prop1}} in the template content will represent data.prop1 in the service instance).
[Service].cached
Is a boolean value that tells QCObjects if the service response needs to be cached or not. When a service is cached, the template content loaded from the service url will be loaded only once. You have to set this value to false for every Service instance you define in order to asure the service is loaded from the resource but not the storage cache.
Methods
[Service].set('prop',value)
Sets a value for a service property.
[Service].get('prop')
Returns the value of a service property
serviceLoader
Loads a service instance and returns a promise that is resolved when the service has a successful response load and is rejected when it fails loading the response.
Usage:
[Promise] serviceLoader(serviceInstance)
Example:
Class('MyTestService',Service,{
name:'myservice',
external:true,
cached:false,
method:'GET',
headers:{'Content-Type':'application/json'},
url:'https://api.github.com/orgs/QuickCorp/repos',
withCredentials:false,
_new_:()=>{
},
done:()=>{
}
});
var service = serviceLoader(New(MyTestService,{
data:{param1:1}
})).then(
(successfulResponse)=>{
console.log(successfulResponse.service.template);
},
(failedResponse)=>{
});
JSONService
Is a built-in definition for a JSON Service Class
Properties
[JSONService].domain
Returns a string with the domain of your application. It is automatically set by QCObjects at the load time.
[JSONService].basePath
Returns a string with the base path url of your application. It is automatically set by QCObjects at the load time.
[JSONService].url
Is a string representing the entire url of the service. It can be absolute or relative to the basePath when it applies. It can be also an external url.
NOTE: To load a service of an external resource you need to specify the external parameter to true using serviceLoader.
[JSONService].name
Is a string representing the name of a component. The name of a service can be any alphanumeric value that identifies the service instance. It isn't a unique ID but only a descriptive name.
[JSONService].method
Is a string representing a HTTP or HTTPS method. Possible values are: "GET", "POST", "PUT", ... any other that is accepted by REST services calls.
[JSONService].data
Is an object representing the data of the service. When QCObjects loads a service. It receives the response and interpretes it as a template. So once a service response is obtained, it will get every property of data object and bind it to a template label representing the same property inside the template content between double brakets (example: {{prop1}} in the template content will represent data.prop1 in the service instance).
[JSONService].cached
Is a boolean value that tells QCObjects if the service response needs to be cached or not. When a service is cached, the template content loaded from the service url will be loaded only once. You have to set this value to false for every Service instance you define in order to asure the service is loaded from the resource but not the storage cache.
Methods
[JSONService].set('prop',value)
Sets a value for a service property.
[JSONService].get('prop')
Returns the value of a service property
Example:
Class('MyTestJSONService',JSONService,{
name:'myJSONservice',
external:true,
cached:false,
method:'GET',
withCredentials:false,
url:'https://api.github.com/orgs/QuickCorp/repos',
_new_:function (){
delete this.headers.charset;
},
done:function (result){
_super_('JSONService','done').call(this,result);
}
});
var service = serviceLoader(New(MyTestJSONService,{
data:{param1:1}
})).then(
(successfulResponse)=>{
console.log(successfulResponse.service.JSONresponse);
},
(failedResponse)=>{
});
ConfigService
Is a built-in Class definition to load the CONFIG settings from a config.json file
Example:
ConfigService.configFileName='config.json';
CONFIG.set('useConfigService',true);
SourceJS
SourceCSS
ArrayList
ArrayCollection
Effect
Timer
SDK
Quick Start
Step 1: Start creating a main import file and name it like: cl.quickcorp.js. Put it into packages/js/ file directory
"use strict";
Import ('external/libs');
Import ('cl.quickcorp.model');
Import ('cl.quickcorp.components');
Import ('cl.quickcorp.controller');
Import ('cl.quickcorp.view');
Package('cl.quickcorp',[
Class('FormValidator',Object,{
}),
]);
Step 2: Then create some services inhereting classes into the file js/packages/cl.quickcorp.services.js :
"use strict";
Package('cl.quickcorp.service',[
Class('JsonService',{
method:"GET",
cached:false,
headers: {
"Content-Type":"application/json",
"charset":"utf-8"
},
JSONresponse: null,
done:function(result){
console.log("***** RECEIVED RESPONSE:");
console.log(result.service.template);
this.JSONresponse = JSON.parse(result.service.template);
alert(this.template);
}
}),
Class('FormSubmitService',{
method:"POST",
cached:false,
headers: {
"Content-Type":"application/json"
},
JSONresponse: null,
done: function(result) {
console.log("***** CALLED FormSubmitService");
this.JSONresponse = JSON.parse(result.service.template);
console.log("***** SUCCESS!")
console.log(this.JSONresponse);
},
fail: function(result) {
console.log("***** ERROR");
}
})
])
Step 3: Now it's time to create the components (cl.quickcorp.components.js)
"use strict";
Package('cl.quickcorp.components',[
Class('FormField',Component,{
cached:false,
reload:true,
createBindingEvents:function (){
var _executeBinding = this.executeBinding;
var thisobj = this;
var _objList = this.body.querySelectorAll(this.fieldType);
for (var _datak=0;_datak<_objList.length;_datak++){
var _obj = _objList[_datak];
_obj.addEventListener('change',function(e){
logger.debug('Executing change event binding');
thisobj.executeBindings();
});
_obj.addEventListener('keydown',function(e){
logger.debug('Executing keydown event binding');
thisobj.executeBindings();
});
}
},
executeBinding:function (_obj){
var _datamodel = _obj.getAttribute('data-field');
logger.debug('Binding '+_datamodel+' for '+this.name);
this.data[_datamodel]=_obj.value;
},
executeBindings:function (){
var _objList = this.body.querySelectorAll(this.fieldType);
for (var _datak=0;_datak<_objList.length;_datak++){
var _obj = _objList[_datak];
var _datamodel = _obj.getAttribute('data-field');
logger.debug('Binding '+_datamodel+' for '+this.name);
this.data[_datamodel]=_obj.value;
}
},
done:function (){
var thisobj = this;
thisobj.executeBindings();
thisobj.createBindingEvents();
logger.debug('Field loaded: '+thisobj.fieldType+'[name='+thisobj.name+']');
}
}),
Class('ButtonField',FormField,{
fieldType:'button'
}),
Class('InputField',FormField,{
fieldType:'input'
}),
Class('TextField',FormField,{
fieldType:'textarea'
}),
Class('EmailField',FormField,{
fieldType:'input'
})
]);
Step 4: Once you have done the above components declaration, you will now want to code your controllers (cl.quickcorp.controller.js)
"use strict";
"use strict";
Package('cl.quickcorp.controller',[
Class('MainController',Object,{
_new_:function (){
logger.debug('MainController Element Initialized');
}
}),
Class('MyAccountController',Object,{
component: null,
done:function (){
var controller = this;
logger.debug('MyAccountController Element Initialized');
this.component.body.setAttribute('loaded',true);
},
_new_:function (o){
this.component = o.component;
}
}),
]);
Step 5: To use into the HTML5 code you only need to do some settings between script tags:
<script>
CONFIG.set('relativeImportPath','js/packages/');
CONFIG.set('componentsBasePath','templates/components/');
CONFIG.set('delayForReady',1); // delay to wait before executing the first ready event, it includes imports
CONFIG.set('preserveComponentBodyTag',false); // don't use <componentBody></componentBody> tag
Import('cl.quickcorp'); # this will import your main file: cl.quickcorp.js into js/packages/ file path
</script>