ObjectLib

Additional object related functions

Summary
ObjectLibAdditional object related functions
Functions
$Owraps an object with the ObjectLib functions.
beforePrepends supplied function to the event chain of an object.
afterAppends supplied function to the event chain of an object.
appendFunctionalias for after
applyToCopies all properties (including Function properties and “hidden”) of an object to another
getKeysreturns a list of non-function properties in an 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 supplied object to JSON (http://www.json.org)
toStructreturns a copy of an object with all the function properties removed
typeOfan enhanced replacement of the the Javscript builtin typeof function.
setByPathsets a property or nested object property of this object
setDefaultPropertiessets default properties on an object
forEachloops over each non-function property of an 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 obj.
filterreturns new Object with only the key/values from obj object that pass a test function
toArrayreturns an Array of objects with a “key” property and a “value” property mapping to the keys and values of this object

Functions

$O

if (typeof $O = = "undefined")

wraps an object with the ObjectLib functions.

Parameters

objobject to wrap

returns obj with all functions in ObjectLib attached, with object as the target

Example

var thing={
name:"thing",
purpose"do Stuff!"
}

//via ObjectLib
ObjectLib.setDefaultProperties(thing,{
newProp:"I'm a new property"
})

//via $O
$O(thing).setDefaultProperties({
newProp2:"another new prop"
})

before

ObjectLib.before=function(obj,
functionName,
functionObj)

Prepends supplied function to the event chain of an 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

var obj={
stuff:function (text){
Myna.println("in orig")
return text + " " + this.myVal;
},
myVal:"firstObj"
}

var obj2={
myVal:"secondObj"
}


ObjectLib.before(obj,"stuff",function(text){
var chain = arguments.callee.chain;
Myna.println("in before")
chain.args[0] = "before " + text
if (text == "dude!"){
// exit now with this return value, nothing after will be executed
chain.exit("sweet!")
}

})

ObjectLib.after(obj,"stuff",function(text){
var chain = arguments.callee.chain;
Myna.println("in after")
return chain.lastReturn + " after "
})

Myna.println(obj.stuff("woot!") +"<hr>");
Myna.println(obj.stuff("dude!") +"<hr>");

obj2.stuff = obj.stuff;
Myna.println(obj2.stuff("woot!") +"<hr>");

after

ObjectLib.after=function(obj,
functionName,
functionObj)

Appends supplied function to the event chain of an 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

(end)

appendFunction

alias for after

applyTo

ObjectLib.applyTo=function(obj,
target,
shouldOverwrite)

Copies all properties (including Function properties and “hidden”) of an object to another

Parameters

objobject to copy from
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 copying the properties of an object to a local scope by applying to ‘this’, or 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
ObjectLib.applyTo(Myna,this);

getKeys

ObjectLib.getKeys = function(obj)

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

Parameters

objobject to examine

Returns

An alphabetized array of properties in an object

getProperties

ObjectLib.getProperties = function(obj)

returns an alphabetized list of all properties in an object

Parameters

objobject to examine

Returns

An alphabetized array of properties in an object

hideProperty

ObjectLib.hideProperty = function(obj,
property)

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

Parameters

objobject to examine
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

ObjectLib.checkRequired=function (obj,
required)

Ensures that certain properties defined.

Parameters

objobject to examine
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 an object.  The first time a property is not found, an exception is raised.

toJson

ObjectLib.toJson=function(obj)

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

Parameters

objobject to convert

Returns

JSON string that represents obj

Detail

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

Attempts to convert obj 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

ObjectLib.toStruct=function(obj)

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

Parameters

objectobject to inspect

typeOf

ObjectLib.typeOf=function(object)

an enhanced replacement of the the Javscript builtin typeof function.

Parameters

objectobject to inspect

Returns

a string representing the type of the object

Detail

The builtin JavaScript typeof function does not identify some stamndard objects, specifically Arrays, Dates, and Nulls.  When running in ObjectLib, it is also important to know when the object is a Java object.  This function returns the standard typeof strings as well as the following:

  • null
  • array
  • class
  • date

setByPath

ObjectLib.setByPath=function (obj,
path,
value)

sets a property or nested object property of this object

Parameters

objobject to apply to
pathdot separated path to the property to set
valuevalue to set

Returns

obj

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 = ObjectLib.setByPath({},"Users.336642.firstName","Mark")
ObjectLib.setByPath(result,"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 = {}
ObjectLib.setByPath(result,"Users[*].firstName","Mark")
ObjectLib.setByPath(result,"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

ObjectLib.setDefaultProperties=function (obj,
defaults,
looseMatch)

sets default properties on an object

Parameters

objobject to apply to
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

obj

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

ObjectLib.forEach=function (obj,
func)

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

Parameters

objObject to loop over
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 an object

Detail

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

Example

var emp ={
id:12,
name:"Bob"
occupation:"being awsome",
isDeceased:false
}

ObjectLib.forEach(emp,function(element,name,object){
alert(name + ": " + element +"<br>");
})

map

ObjectLib.map=function (obj,
func)

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

Parameters

objObject to loop over
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
}

var fixedEmp = ObjectLib.map(emp,function(element,name,object){
if (element === null) {
return ""
} else {
return element
}
})

filter

ObjectLib.filter=function (obj,
func)

returns new Object with only the key/values from obj 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
}

var fixedEmp = ObjectLib.filter(emp,function(element,name,object){
return element !== null
})

toArray

ObjectLib.toArray=function (obj,
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

objObject to loop over
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 = ObjectLib.toArray(obj)
//returns [{key:"first_name",value:"Bob"},{key:"lasst_name",value:"Dobb"}]
if (typeof $O = = "undefined")
wraps an object with the ObjectLib functions.
ObjectLib.before=function(obj,
functionName,
functionObj)
Prepends supplied function to the event chain of an object.
ObjectLib.after=function(obj,
functionName,
functionObj)
Appends supplied function to the event chain of an object.
ObjectLib.applyTo=function(obj,
target,
shouldOverwrite)
Copies all properties (including Function properties and “hidden”) of an object to another
ObjectLib.getKeys = function(obj)
returns a list of non-function properties in an object by order of appearance
ObjectLib.getProperties = function(obj)
returns an alphabetized list of all properties in an object
ObjectLib.hideProperty = function(obj,
property)
Server-Only set the “DONTENUM” attribute of the supplied property
ObjectLib.checkRequired=function (obj,
required)
Ensures that certain properties defined.
ObjectLib.toJson=function(obj)
Converts the supplied object to JSON (http://www.json.org)
ObjectLib.toStruct=function(obj)
returns a copy of an object with all the function properties removed
ObjectLib.typeOf=function(object)
an enhanced replacement of the the Javscript builtin typeof function.
ObjectLib.setByPath=function (obj,
path,
value)
sets a property or nested object property of this object
ObjectLib.setDefaultProperties=function (obj,
defaults,
looseMatch)
sets default properties on an object
ObjectLib.forEach=function (obj,
func)
loops over each non-function property of an object an executes the supplied function against it.
ObjectLib.map=function (obj,
func)
returns new Object with the results of calling a provided function on every non-function element in obj.
ObjectLib.filter=function (obj,
func)
returns new Object with only the key/values from obj object that pass a test function
ObjectLib.toArray=function (obj,
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