Object

Additional functions on the JS Object object

Each function here comes from <ObjectLib.js>, so including this file is only necessary to apply these functions to the Object prototype

Summary
ObjectAdditional functions on the JS Object object
Functions
beforePrepends supplied function to the event chain of this object.
afterAppends supplied function to the event chain of this object.
old_before/* Function: old_after DEPRECATED This function is for backwards compatibility only.
old_afterDEPRECATED This function is for backwards compatibility only.
appendFunctionalias for after
applyToCopies all properties (including Function properties) of this object to another
getKeysreturns a list of non-function properties in this object by order of appearance
getPropertiesreturns an alphabetized list of all properties in an object
hidePropertyServer-Only set the “DONTENUM” attribute of the supplied property
checkRequiredEnsures that certain properties defined.
toJsonConverts the this object to JSON (http://www.json.org)
toStructreturns a copy of an object with all the function properties removed
setByPathsets a property or nested object property of this object
setDefaultPropertiessets default properties on this object
forEachloops over each non-function property of this object an executes the supplied function against it.
mapreturns new Object with the results of calling a provided function on every non-function element in this.
filterreturns new Object with only the key/values from this object that pass a test function
copyreturns a new object with the same properties as the supplied object
createProxyreturns a proxy object where the functions and properties actually refer to this object
toArrayreturns an Array of objects with a “key” property and a “value” property mapping to the keys and values of this object

Functions

before

Object.prototype.before=function(functionName,
functionObj)

Prepends supplied function to the event chain of this object.

Parameters

objobject to apply to
functionNamename of the function on an object to modify
functionObjfunction object to append

Detail

Existing functions are preserved and executed after the supplied function.  This is a shortcut for creating chain functions and is the equivalent of

obj[functionName] = obj[functionName].before(functionObj)

See Function.createChainFunction for how chain functions work.

Examples

// example of creating an audit function
dm = new Myna.DataManager("hr")
dm.managerTemplate.before("saveField",function(fieldName,newVal){
var chain = arguments.callee.chain;
//save audit table manager
if (!this.audiManager) {
this.auditManager = new Myna.DataManager("audit_db").getManager("audit_Table")
}

this.audiManager.create({
ts:new Date(),
user_id:$cookie.getAuthUserId,
table:this.table.tableName,
column:fieldName,
old_val:this.data[fieldName],
new_val:newVal
})
})

after

Object.prototype.after=function(functionName,
functionObj)

Appends supplied function to the event chain of this object.

Parameters

objobject to apply to
functionNamename of the function on an object to modify
functionObjfunction object to append

Detail

Existing functions are preserved and executed after the supplied function.  This is a shortcut for creating chain functions and is the equivalent of

obj[functionName] = obj[functionName].after(functionObj)

See Function.createChainFunction for how chain functions work.

Examples

// example of adding extra functions to bean objects
dm = new Myna.DataManager("hr")
dm.managerTemplate.after("getById",function(id){
var chain = arguments.callee.chain;
if (this.table.tableName == "employee"){
chain.lastReturn.getDirectReports = function(){
return this.manager.findBeans({
manager_id:this.employee_id
})
}
}
return chain.lastReturn;
})

old_before

Object.prototype.old_before=function(functionName,
functionObj)

/* Function: old_after DEPRECATED This function is for backwards compatibility only.  See before

Prepends supplied function to the event chain of this object.

Parameters

functionNamename of the function on an object to modify
functionObjfunction object to append

Detail

Existing functions are preserved and executed after the supplied function.

The resulting chain will return

  • The returnValue property of arguments.callee.chain.returnValue, if defined
  • Or undefined if functionObj returns false
  • Or the result of the original function

functionObj will have properties added to it that can be accessed via arguments.callee.chain from inside the function

arguments.callee.chain

returnValuedefault undefined If this is defined after functionObj completes, then this value will be returned instead of executing the original function.
originalFunctionThis is a reference to the original function, bound to this object.  This is useful in conjunction with returnValue to call the original function with altered parameters and return the result

Examples

// example of setting calculated values during object creation
dm = new Myna.DataManager("hr")
dm.managerTemplate.before("create",function(obj){
var chain = arguments.callee.chain;
if (this.table.tableName == "employee"){
if (!obj.salary){
obj.salary = calcBaseSalary(obj)
}
chain.returnValue=chain.originalFunction(obj);
}
})

old_after

Object.prototype.old_after=function(functionName,
functionObj)

DEPRECATED This function is for backwards compatibility only.  See after

Appends supplied function to the event chain of this object.

Parameters

functionNamename of the function on an object to modify
functionObjfunction object to append

Detail

Existing functions are preserved and executed in the order they were declared.  If the function functionName does not exist, it will be created.

The resulting chain will return the result of the original function, unless overridden in arguments.callee.chain.returnValue

functionObj will have properties added to it that can be accessed via arguments.callee.chain from inside the function.

arguments.callee.chain

returnValuedefault return value from original function This is the value that will be returned.  This can be overwritten by functionObj
originalFunctionThis is a reference to the original function, bound to this object.

Examples

// example of adding extra functions to bean objects
dm = new Myna.DataManager("hr")
dm.managerTemplate.after("getById",function(id){
var chain = arguments.callee.chain;
if (this.table.tableName == "employee"){
chain.returnValue.getDirectReports = function(){
return this.manager.findBeans({
manager_id:this.employee_id
})
}
}

})

appendFunction

alias for after

applyTo

Object.prototype.applyTo=function(target,
shouldOverwrite)

Copies all properties (including Function properties) of this object to another

Parameters

targetobject to copy to
shouldOverwriteOptional, default false Should existing properties in target be replaced by the properties in source?

Returns

target

Detail

This can be used for simulating inheritance (even multiple inheritance) on instantiated objects by copying the properties of another object

Examples

// Make Myna's functions such as abort() and dump() available
// without the Myna prefix
Myna.applyTo(this);

getKeys

Object.prototype.getKeys = function(obj)

returns a list of non-function properties in this object by order of appearance

Parameters

objOptional, default this object to examine

Returns

An alphabetized array of properties in an object

getProperties

Object.prototype.getProperties = function(obj)

returns an alphabetized list of all properties in an object

Parameters

objOptional, default this object to examine

Returns

An alphabetized array of properties in an object

hideProperty

Object.prototype.hideProperty = function(property)

Server-Only set the “DONTENUM” attribute of the supplied property

Parameters

propertypropery to modify

Detail

Set the the “DONTENUM” attribute on the defined property.  This means that this property will not appear in getProperties or <Myna.Dump> or forEach or any other function that loops over enumerable properties.  Use this to “hide” functions and properties that you do not want to be considered “data”

checkRequired

Object.prototype.checkRequired=function (required)

Ensures that certain properties defined.

Parameters

requiredArray of property name strings to look for

Returns

void

Detail

This function is intended for Javascript Objects being used as data containers.  Particularly JS objects passed as function parameters.

This function simply checks to see if every string in the required array has a corresponding property in this Object.  The first time a property is not found, an exception is raised.

toJson

Object.prototype.toJson=function(indent)

Converts the this object to JSON (http://www.json.org)

Returns

JSON string that represents this object

Detail

Adapted from http://www.json.org/json.js

Attempts to convert this object to JSON.  This is best used on simple Objects and Arrays.

Example

//this code might be called by an AJAX callback
var qry=new Query({
dataSource:":mem:",
sql:"select * from event"
});
$res.print(qry.data.toJson());

toStruct

Object.prototype.toStruct=function()

returns a copy of an object with all the function properties removed

Parameters

objectobject to inspect

setByPath

Object.prototype.setByPath=function (path,
value)

sets a property or nested object property of this object

Parameters

pathdot or array separated path to the property to set
valuevalue to set

Returns

this

Detail

Often times it is convenient to store key value pairs as a dot separated path and a value, especially in HTML forms which do not support structured parameters like so:

<input name="Users.336642.firstName" value = "Mark">

Calling this function against an object will walk the nested object tree, creating objects as necessary, until the final property is set to the value

Example

var result = {}
result.setByPath("Users.336642.firstName","Mark")
result.setByPath("Users.536642.firstName","Bob")
// result Equals
// {
// Users:{
// "336642":{
// firstName:"Mark"
// },
// "536642":{
// firstName:"Bob"
// },
// }
// }


// the * means append otherwise the array index is used even if out of order
var result = {}
result.setByPath("Users[*].firstName","Mark")
result.setByPath("Users[0].firstName","Bob")
// result Equals
// {
// Users:[
// {
// firstName:"Bob"
// },
// {
// firstName:"Mark"
// }
// ]
// }

Note

This function is applied automatically against $req.data for params that contain periods

setDefaultProperties

Object.prototype.setDefaultProperties=function (defaults,
looseMatch)

sets default properties on this object

Parameters

defaultsObject that represents the default properties
looseMatchIf true, consider “null” values and 0 length strings to be the same as undefined.  By default, only strictly undefined properties are overwritten by their defaults.

Returns

this

Detail

Every property in defaults is checked against this.  If the property is undefined in this, it is copied from defaults.

Example

$res.data.setDefaultProperties({
name:"bob",
isDeceased:false
});

forEach

Object.prototype.forEach=function (func)

loops over each non-function property of this object an executes the supplied function against it.

Parameters

callbackFunction to execute.  See below for the parameters it will be passed

Callback Parameters

elementthe value of property
namethe name of the property
indexordinal of this element
objecta reference to this object

Detail

This function is modeled after the JS function Array.forEach.

Example

{
id:12,
name:"Bob"
occupation:"being awsome",
isDeceased:false
}.forEach(function(element,name,object){
ObjectLib.print(name + ": " + element +"<br>");
})

map

Object.prototype.map=function map(func)

returns new Object with the results of calling a provided function on every non-function element in this.

Parameters

funcFunction to execute.  See below for the parameters it will be passed

Callback Parameters

elementthe value of property
namethe name of the property
indexordinal of this element
objecta reference to this object

Detail

This function is modeled after the JS function Array.map.

Example

//make sure null values come across as empty strings
var emp = {
id:12,
name:"Bob",
age:null,
occupation:"being awesome",
isDeceased:false
}.map(function(element,name,object){
if (element === null) {
return ""
} else {
return element
}
})

filter

Object.prototype.filter=function (func)

returns new Object with only the key/values from this object that pass a test function

Parameters

objObject to loop over
funcFunction to execute. return true to include this key/value See below for the parameters it will be passed

Callback Parameters

elementthe value of property
namethe name of the property
indexordinal of this element
objecta reference to this object

Detail

This function is modeled after the JS function Array.filter.

Example

// remove null values
var emp = {
id:12,
name:"Bob",
age:null,
occupation:"being awesome",
isDeceased:false
}.filter(function(element,name,object){
return element !== null
})

copy

Object.prototype.copy=function (deep)

returns a new object with the same properties as the supplied object

Parameters

objobject to apply to
deepoptional, default false If true, a deep copy is made where no property or child of a property in the new object is shared with the original object.

Only works with pure JavaScript, and functions will be stripped

Detail

by default, this performs a shallow copy by creating a new object and copying the properties of the old object onto it.

if deep is true, then the object is decompiled to source and the compiled as a new object.  Deep copies will fail if the object contains java objects, and all functions are removed, regardless.  Deep copies are useful for “sanitizing” a complex data object for storage, transmission, or return from a function.

Example

var dontChangeName =function(obj){
//make a shallow copy of object so we can alter it's properties
var myObj = obj.copy();
myObj.name = "stan";
}

var bob ={
name:"bob"
}
dontChangeName(bob);
//bob is still "bob"


var dataChunk={
_data:[1,2,3,4],
getData:function(){
//deep copy, user can't change contents of this._data
return this._data.copy(true);
}
}
var data = dataChunk.getData();
data.push(5); //doesn't affect dataChunk._data;

createProxy

Object.prototype.createProxy=function Object_createProxy(target,
overwrite)

returns a proxy object where the functions and properties actually refer to this object

Parameters

targetOptional, default {} If defined, properties and functions will be overlaid on the target object instead of creating a new object.
overwriteOptional,default false Only applies if target is defined. if true, then existing properties on _target will be overwritten by this proxy versions.

Detail

This purpose of this function is to make composting easier.  A great example is if you want to extend a DAO without using inheritance, like so:

toArray

Object.prototype.toArray=function (includeFunctions,
localOnly)

returns an Array of objects with a “key” property and a “value” property mapping to the keys and values of this object

Parameters

includeFunctionsOptional, default false By default only properties that are not functions are mapped.  Set this to true to include functions
localOnlyOptional, default false By default both local and prototype properties are mapped, set this to true limit to only local properties

Note

if Myna.DataSet is available, then a DataSet is returned, which allows recreating the object via result.toMap(“key”,”value”)

Example

var obj = {first_name:"Bob",last_name:"Dobb"}
var array = obj.toArray()
//returns [{key:"first_name",value:"Bob"},{key:"lasst_name",value:"Dobb"}]
Object.prototype.before=function(functionName,
functionObj)
Prepends supplied function to the event chain of this object.
Object.prototype.after=function(functionName,
functionObj)
Appends supplied function to the event chain of this object.
Object.prototype.old_before=function(functionName,
functionObj)
/* Function: old_after DEPRECATED This function is for backwards compatibility only.
Object.prototype.old_after=function(functionName,
functionObj)
DEPRECATED This function is for backwards compatibility only.
Object.prototype.applyTo=function(target,
shouldOverwrite)
Copies all properties (including Function properties) of this object to another
Object.prototype.getKeys = function(obj)
returns a list of non-function properties in this object by order of appearance
Object.prototype.getProperties = function(obj)
returns an alphabetized list of all properties in an object
Object.prototype.hideProperty = function(property)
Server-Only set the “DONTENUM” attribute of the supplied property
Object.prototype.checkRequired=function (required)
Ensures that certain properties defined.
Object.prototype.toJson=function(indent)
Converts the this object to JSON (http://www.json.org)
Object.prototype.toStruct=function()
returns a copy of an object with all the function properties removed
Object.prototype.setByPath=function (path,
value)
sets a property or nested object property of this object
Object.prototype.setDefaultProperties=function (defaults,
looseMatch)
sets default properties on this object
Object.prototype.forEach=function (func)
loops over each non-function property of this object an executes the supplied function against it.
Object.prototype.map=function map(func)
returns new Object with the results of calling a provided function on every non-function element in this.
Object.prototype.filter=function (func)
returns new Object with only the key/values from this object that pass a test function
Object.prototype.copy=function (deep)
returns a new object with the same properties as the supplied object
Object.prototype.createProxy=function Object_createProxy(target,
overwrite)
returns a proxy object where the functions and properties actually refer to this object
Object.prototype.toArray=function (includeFunctions,
localOnly)
returns an Array of objects with a “key” property and a “value” property mapping to the keys and values of this object
Function.createChainFunction=function(initialChain)
returns a function that will execute a chain of functions when called.
if (!Array.prototype.forEach)
Executes a provided function once per array element.
if (!Array.prototype.map)
Creates a new array with the results of calling a provided function on every element in this array.
if (!Array.prototype.filter)
Creates a new array with all elements that pass the test implemented by the provided function.
A specialized array for working with tabular data