Language Helpers page
JavaScriptMVC has several lightweight language helper plugins.
Methods useful for comparing Objects. For example, if two objects are thesame:
$.Object.same({foo: "bar"}, {foo: "bar"});
Makes an Object's properties observable:
var person = new $.Observe({ name: "Justin" })
person.bind('change', function(){ ... })
person.attr('name', "Brian");
String helpers capitalize, underscore, and perform similar manipulationson strings. They can also lookup a value in an object:
$.String.getObject("foo.bar",{foo: {bar: "car"}})
Used to create or consume JSON strings.
Used for vector math.
jQuery.Object class
Object contains several helper methods that help compare objects.
same
Returns true if two objects are similar.
$.Object.same({foo: "bar"} , {bar: "foo"}) //-> false
subset
Returns true if an object is a set of another set.
$.Object.subset({}, {foo: "bar"} ) //-> true
subsets
Returns the subsets of an object
$.Object.subsets({userId: 20},
[
{userId: 20, limit: 30},
{userId: 5},
{}
])
//-> [{userId: 20, limit: 30}]
jQuery.Object.same function
Returns if two objects are the same. It takes an optional compares objectthat can be used to make comparisons.
This function does not work with objects that create circular references.
Examples
$.Object.same({name: "Justin"},
{name: "JUSTIN"}) //-> false
// ignore the name property
$.Object.same({name: "Brian"},
{name: "JUSTIN"},
{name: null}) //->true
// ignore case
$.Object.same({name: "Justin"},
{name: "JUSTIN"},
{name: "i"}) //->true
// deep rule
$.Object.same({ person : { name: "Justin" } },
{ person : { name: "JUSTIN" } },
{ person : { name: "i" } }) //-> true
// supplied compare function
$.Object.same({age: "Thirty"},
{age: 30},
{age: function( a, b ){
if( a == "Thirty" ) {
a = 30
}
if( b == "Thirty" ) {
b = 30
}
return a === b;
}}) //->true
API
$.Object.same(a, b, compares,aParent, bParent, deep) -> undefined
a {Object}
an object to compare
b {Object}
an object to compare
compares {optional:Object}
an object that indicates how to compare specific properties. Typicallythis is a name / value pair
$.Object.same({name: "Justin"},{name: "JUSTIN"},{name: "i"})
There are two compare functions that you can specify with a string:
aParent {}
bParent {}
deep {optional:Object}
used internally
returns {undefined}
jQuery.Object.subset function
Compares if checkSet is a subset of set
API
$.Object.subset(subset, set,compares, checkSet, checkPropCount) -> undefined
subset {}
set {Object}
compares {optional:Object}
checkSet {Object}
checkPropCount {optional:Object}
returns {undefined}
jQuery.Object.subsets function
Returns the sets in 'sets' that are a subset of checkSet
API
$.Object.subsets(checkSet, sets,compares) -> undefined
checkSet {Object}
sets {Object}
compares {}
returns {undefined}
jQuery.Observe class
test: qunit.html
Observe provides the awesome observable pattern for JavaScript Objects andArrays. It lets you
Creating an $.Observe
To create an $.Observe, or $.Observe.List, you can simply use the $.O(data) shortcut like:
var person = $.O({name: 'justin', age: 29}),
hobbies = $.O(['programming', 'basketball', 'nose picking'])
Depending on the type of data passed to $.O, it will create an instance ofeither:
$.Observe.List and $.Observe are very similar. In fact, $.Observe.Listinherits $.Observe and only adds a few extra methods for manipulating arrayslike push.Go to $.Observe.Listfor more information about $.Observe.List.
You can also create a new $.Observe simply by pass it the datayou want to observe:
var data = {
addresses : [
{
city: 'Chicago',
state: 'IL'
},
{
city: 'Boston',
state : 'MA'
}
],
name : "Justin Meyer"
},
o = new$.Observe(data);
o now represents an observablecopy of data.
Getting and Setting Properties
Use attrand attrsto get and set properties.
For example, you can read the property values of o with observe.attr( name ) like:
// read name
o.attr('name') //-> Justin Meyer
And set property names of o with observe.attr( name, value ) like:
// update name
o.attr('name', "Brian Moschel") //-> o
Observe handles nested data. Nested Objects and Arrays are converted to$.Observe and $.Observe.Lists. This lets you read nested properties and use$.Observe methods on them. The following updates the second address (Boston) to'New York':
o.attr('addresses.1').attrs({
city: 'New York',
state: 'NY'
})
attrs() can be used toget all properties back from the observe:
o.attrs() // ->
{
addresses : [
{
city: 'Chicago',
state: 'IL'
},
{
city: 'New York',
state : 'MA'
}
],
name : "Brian Moschel"
}
Listening to property changes
When a property value is changed, it creates events that you can listento. There are two ways to listen for events:
With bind("change" , handler( ev, attr, how, newVal, oldVal ) ), you can listen to any change that happens within theobserve. The handler gets called with the property name that was changed, howit was changed ['add','remove','set'], the new value and the old value.
o.bind('change', function( ev, attr, how, nevVal, oldVal ) {
})
delegate( attr, event, handler(ev, newVal, oldVal ) ) lets you listen to a specific event on a specificattribute.
// listen for name changes
o.delegate("name","set", function(){
})
Delegate lets you specify multiple attributes and values to match for thecallback. For example,
r = $.O({type: "video", id : 5})
r.delegate("type=images id","set", function(){})
This is used heavily by $.route.
API
$.Observe(obj) ->jquery.observe
obj {Object}
a JavaScript Object that will be converted to an observable
returns {jquery.observe}
jQuery.Observe.List class
inherits: jQuery.Observe
An observable list. You can listen to when items are push, popped,spliced, shifted, and unshifted on this array.
jQuery.Observe.List.prototype.attrs function
Updates an array with a new array. It is able to handle removes in themiddle of the array.
API
observe.list.attrs(props, remove)-> undefined
props {Array}
remove {Boolean}
returns {undefined}
jQuery.Observe.List.prototype.indexOf function
Returns the position of the item in the array. Returns -1 if the item isnot in the array.
API
observe.list.indexOf(item) ->Number
item {Object}
returns {Number}
jQuery.Observe.List.prototype.pop function
Removes an item from the end of the list.
var l = new $.Observe.List([0,1,2]);
l.bind('change', function(
ev, // the change event
attr, // the attr that was changed, formultiple items, "*" is used
how, // "remove"
newVals, // undefined
oldVals, // 2
where // the location where these items whereadded
) {
})
l.pop();
API
observe.list.pop() -> Object
returns {Object}
the element at the end of the list
jQuery.Observe.List.prototype.push function
Add items to the end of the list.
var l = new $.Observe.List([]);
l.bind('change', function(
ev, // the change event
attr, // the attr that was changed, formultiple items, "*" is used
how, // "add"
newVals, // an array of new values pushed
oldVals, // undefined
where // the location where these items whereadded
) {
})
l.push('0','1','2');
API
observe.list.push() -> Number
returns {Number}
the number of items in the array
jQuery.Observe.List.prototype.serialize function
Returns the serialized form of this list.
API
observe.list.serialize() ->undefined
returns {undefined}
jQuery.Observe.List.prototype.shift function
Removes an item from the start of the list. This is very similar to[jQuery.Observe.prototype.pop].
API
observe.list.shift() -> Object
returns {Object}
the element at the start of the list
Remove items or add items from a specific point in thelist.
The following creates a list of numbers and replaces 2 and3 with "a", and "b".
varl =
new$.Observe.List([
0,
1,
2,
3]);
l.bind(
'change',
function( ev, attr, how, newVals, oldVals, where ) {... })
l.splice(
1,
2,
"a",
"b");
// results in [0,"a","b",3]
This creates 2 change events. The first event is theremoval of numbers one and two where it's callback values will be:
The second change event is the addition of the"a", and "b" values where the callback values will be:
observe.list.splice(index, count, added) -> undefined
{Number}
where to start removing or adding items
{Object}
the number of items to remove
{optional:Object}
an object to add to
{undefined}
jQuery.Observe.List.prototype.unshift function
Add items to the start of the list. This is very similar to[jQuery.Observe.prototype.push].
API
observe.list.unshift()
jQuery.Observe.prototype.attr function
Get or set an attribute on the observe.
o = new$.Observe({});
// sets a user property
o.attr('user',{name: 'hank'});
// read the user's name
o.attr('user.name') //-> 'hank'
If a value is set for the first time, it will trigger an 'add' and 'set' change event. Once the value has been added. Any futurevalue changes will trigger only 'set' events.
API
observe.attr(attr, val) ->Object
attr {String}
the attribute to read or write.
o.attr('name') //-> reads the name
o.attr('name', 'Justin') //-> writes the name
You can read or write deep property names. For example:
o.attr('person', {name: 'Justin'})
o.attr('person.name') //-> 'Justin'
val {optional:Object}
if provided, sets the value.
returns {Object}
the observable or the attribute property.
If you are reading, the property value is returned:
o.attr('name') //-> Justin
If you are writing, the observe is returned for chaining:
o.attr('name',"Brian").attr('name') //-> Justin
jQuery.Observe.prototype.attrs function
Set multiple properties on the observable
API
observe.attrs(props, remove)-> undefined
props {Object}
remove {Boolean}
true if you should remove properties that are not in props
returns {undefined}
jQuery.Observe.prototype.bind function
Listens to changes on a jQuery.Observe.
When attributes of an observe change, including attributes on nestedobjects, a 'change' event is triggered on the observe. These events come inthree flavors:
The change event is fired with:
Example:
o = new$.Observe({name : "Payal"});
o.bind('change', function(ev, attr, how, newVal, oldVal){
// ev -> {type: 'change'}
// attr -> "name"
// how -> "add"
// newVal-> "Justin"
// oldVal-> undefined
})
o.attr('name', 'Justin')
Listening to change is only useful for when you want to know every change onan Observe. For most applications, delegateis much more useful as it lets you listen to specific attribute changes andsepecific types of changes.
API
observe.bind(eventType,handler(event, attr, how, newVal, oldVal)) -> undefined
eventType {String}
the event name. Currently, only 'change' events are supported. For morefine grained control, use jQuery.Observe.prototype.delegate.
handler(event, attr, how, newVal, oldVal) {Function}
A callback function where
· jQuery.Observe.prototype.delegate function
· plugin:jquery/lang/observe/delegate
· Source
· Listen for changesin a child attribute from the parent. The child attribute does not have toexist.
· // create anobservable
· var observe = $.O({
· foo : {
· bar : "Hello World"
· }
· })
·
· //listen tochanges on a property
· observe.delegate("foo.bar","change", function(ev, prop, how, newVal,oldVal){
· // foo.bar has been added, set, or removed
· this //->
· });
·
· // change theproperty
· observe.attr('foo.bar',"Goodbye Cruel World")
· Types of events
· Delegate lets youlisten to add, set, remove, and change events on property.
· add
· An add event isfired when a new property has been added.
· var o = new$.Observe({});
· o.delegate("name","add", function(ev, value){
· // called once
· $('#name').show()
· })
· o.attr('name',"Justin")
· o.attr('name',"Brian");
· Listening to addevents is useful for 'setup' functionality (in this case showing the #name element.
· set
· Set events are firedwhen a property takes on a new value. set events are always fired after an add.
· o.delegate("name","set", function(ev, value){
· // called twice
· $('#name').text(value)
· })
· o.attr('name',"Justin")
· o.attr('name',"Brian");
· remove
· Remove events arefired after a property is removed.
· o.delegate("name","remove", function(ev){
· // called once
· $('#name').text(value)
· })
· o.attr('name',"Justin");
· o.removeAttr('name');
· Wildcards -matching multiple properties
· Sometimes, youwant to know when any property within some part of an observe has changed.Delegate lets you use wildcards to match any property name. The followinglistens for any change on an attribute of the params attribute:
· var o = $.Observe({
· options : {
· limit : 100,
· offset: 0,
· params : {
· parentId: 5
· }
· }
· })
· o.delegate('options.*','change', function(){
· alert('1');
· })
· o.delegate('options.**','change', function(){
· alert('2');
· })
·
· // alerts 1
· // alerts 2
· o.attr('options.offset',100)
·
· // alerts 2
· o.attr('options.params.parentId',6);
· Using a singlewildcard () matches single level properties. Using a double wildcard (*) matches any deep property.
· Listening onmultiple properties and values
· Delegate lets youlisten on multiple values at once, for example,
· API
· observe.delegate(selector, event, cb) -> jQuery.Delegate
· selector {String}
· the attributes youwant to listen for changes in.
· event {String}
· the event name
· cb {Function}
· the callbackhandler
· returns {jQuery.Delegate}
· the delegate forchaining
· jQuery.Observe.prototype.each function
· Source
· Iterates througheach attribute, calling handler with each attribute name and value.
· new Observe({foo: 'bar'})
· .each(function(name, value){
· equals(name, 'foo')
· equals(value,'bar')
· })
· API
· observe.each(handler(attrName,value)) -> jQuery.Observe
· handler(attrName,value){function}
· A function thatwill get called back with the name and value of each attribute on the observe.
· Returning false breaks the looping. The following will never log 3:
· new Observe({a : 1, b : 2, c: 3})
· .each(function(name, value){
· console.log(value)
· if(name == 2){
· return false;
· }
· })
· returns {jQuery.Observe}
· the originalobservable.
· jQuery.Observe.prototype.removeAttr function
· Source
· Removes a property
· o = new$.Observe({foo: 'bar'});
· o.removeAttr('foo'); //-> 'bar'
· This creates a 'remove' change event. Learn more about events in bindand delegate.
· API
· observe.removeAttr(attr) -> Object
· attr {String}
· the attribute nameto remove.
· returns {Object}
· the value that wasremoved.
· jQuery.Observe.prototype.serialize function
· Source
· Get the serializedObject form of the observe. Serialized data is typically used to send back to aserver.
· o.serialize() //-> { name: 'Justin' }
· Serializecurrently returns the same data as jQuery.Observe.prototype.attrs.However, in future versions, serialize will be able to return serialized datasimilar to jQuery.Model.The following will work:
· new Observe({time: new Date()})
· .serialize() //-> { time: 1319666613663 }
· API
· observe.serialize() -> Object
· returns {Object}
· a JavaScriptObject that can be serialized with JSON.stringify or othermethods.
jQuery.Observe.prototype.unbind function
Unbinds a listener. This uses jQuery.unbindand works very similar. This means you can use namespaces or unbind all eventhandlers for a given event:
// unbind a specific event handler
o.unbind('change', handler)
// unbind all change event handlers bound with the
// foo namespace
o.unbind('change.foo')
// unbind all change event handlers
o.unbind('change')
API
observe.unbind(eventType,handler) -> jQuery.Observe
eventType {String}
handler {optional:Function}
returns {jQuery.Observe}
the original observe for chaining.
jQuery.Observe.prototype.undelegate function
plugin: jquery/lang/observe/delegate
Removes a delegate event handler.
observe.undelegate("name","set", function(){ ... })
API
observe.undelegate(selector,event, cb) -> jQuery.Delegate
selector {String}
the attribute name of the object you want to undelegate from.
event {String}
the event name
cb {Function}
the callback handler
returns {jQuery.Delegate}
the delegate for chaining
jQuery.String class
A collection of useful string helpers. Available helpers are:
· $.String.sub("foo {bar}",{bar:"far"})
//-> "foofar"
jQuery.String.camelize function
Capitalizes a string from something undercored. Examples:
jQuery.String.camelize("one_two") //-> "oneTwo"
"three-four".camelize() //->threeFour
API
$.String.camelize(s) -> String
s {String}
returns {String}
a the camelized string
jQuery.String.capitalize function
Capitalizes a string
API
$.String.capitalize(s, cache)-> String
s {String}
the string.
cache {}
returns {String}
a string with the first character capitalized.
© Bitovi - JavaScriptMVCTraining and Support
jQuery.String.classize function
Like camelize,but the first part is also capitalized
API
$.String.classize(s, join) ->String
s {String}
join {}
returns {String}
the classized string
jQuery.String.deparam function
Takes a string of name value pairs and returns a Object literal thatrepresents those params.
API
$.String.deparam(params) ->Object
params {String}
a string like "foo=bar&person[age]=3"
returns {Object}
A JavaScript Object that represents the params:
{
foo: "bar",
person: {
age: "3"
}
}
jQuery.String.getObject function
Gets an object from a string. It can also modify objects on the 'objectpath' by removing or adding properties.
Foo = {Bar: {Zar: {"Ted"}}}
$.String.getObject("Foo.Bar.Zar") //->"Ted"
API
$.String.getObject(name, roots,add) -> Object
name {String}
the name of the object to look for
roots {optional:Array}
an array of root objects to look for the name. If roots is not provided,the window is used.
add {optional:Boolean}
true to add missing objects to the path. false to remove found properties.undefined to not modify the root object
returns {Object}
The object.
jQuery.String.niceName function
Like classize,but a space separates each 'word'
jQuery.String.niceName("one_two") //-> "OneTwo"
API
$.String.niceName(s) -> String
s {String}
returns {String}
the niceName
jQuery.String.rsplit function
Splits a string with a regex correctly cross browser
$.String.rsplit("a.b.c.d", /\./) //-> ['a','b','c','d']
API
$.String.rsplit(string, regex)-> Array
string {String}
The string to split
regex {RegExp}
A regular expression
returns {Array}
An array of strings
jQuery.String.sub function
Returns a string with {param} replaced values from data.
$.String.sub("foo {bar}",{bar: "far"})
//-> "foo far"
API
$.String.sub(s, data, remove)-> undefined
s {String}
The string to replace
data {Object}
The data to be used to look for properties. If it's an array, multipleobjects can be used.
remove {optional:Boolean}
if a match is found, remove the property from the object
returns {undefined}
jQuery.String.underscore function
Underscores a string.
jQuery.String.underscore("OneTwo") //->"one_two"
API
$.String.underscore(s) ->String
s {String}
returns {String}
the underscored string
jQuery.toJSON page
jQuery.toJSON( json-serializble )
Converts the given argument into a JSON respresentation.
If an object has a "toJSON" function, that will be used to getthe representation. Non-integer/string keys are skipped in the object, as arekeys that point to a function.
json-serializble: The thing to be converted.
jQuery.evalJSON function
Evaluates a given piece of json source.
Evaluates a given piece of json source.
API
$.evalJSON(src) -> undefined
src {}
returns {undefined}
jQuery.quoteString function
Returns a string-repr of a string, escaping quotes intelligently.
Mostly a support function for toJSON.
Examples:
jQuery.quoteString("apple") //-> "apple"
jQuery.quoteString('"Where are we going?", she asked.')
// -> "\"Where arewe going?\", she asked."
Returns a string-repr of a string, escaping quotes intelligently.
Mostly a support function for toJSON.
Examples:
jQuery.quoteString("apple") //-> "apple"
jQuery.quoteString('"Where are we going?", she asked.')
// -> "\"Where arewe going?\", she asked."
API
$.quoteString(string) ->undefined
string {}
returns {undefined}
jQuery.secureEvalJSON function
Evals JSON in a way that is more secure.
Evals JSON in a way that is more secure.
API
$.secureEvalJSON(src) ->undefined
src {}
returns {undefined}
jQuery.Vector class
A vector class
Constructor
creates a new vector instance from the arguments. Example:
new jQuery.Vector(1,2)
new $.Vector() -> jquery.vector
returns {jquery.vector}
jQuery.Vector.prototype.app function
Applys the function to every item in the vector. Returns the new vector.
API
vector.app(f) -> jQuery.Vector
f {Function}
returns {jQuery.Vector}
new vector class.
jQuery.Vector.prototype.equals function
Returns the current vector if it is equal to the vector passed in.
False if otherwise.
API
vector.equals() ->jQuery.Vector
returns {jQuery.Vector}
jQuery.Vector.prototype.height attribute
Returns the 2nd value of the vector
jQuery.Vector.prototype.left attribute
same as x()
jQuery.Vector.prototype.minus function
Like plus but subtracts 2 vectors
API
vector.minus() -> jQuery.Vector
returns {jQuery.Vector}
jQuery.Vector.prototype.plus function
Adds two vectors together. Example:
new Vector(1,2).plus(2,3) //-> <3,5>
new Vector(3,5).plus(new Vector(4,5)) //-><7,10>
API
vector.plus() -> undefined
jQuery.Vector.prototype.top attribute
Same as y()
jQuery.Vector.prototype.toString function
returns (x,y)
API
vector.toString() -> String
returns {String}
jQuery.Vector.prototype.update function
Replaces the vectors contents
API
vector.update(array) ->undefined
array {Object}
returns {undefined}
jQuery.Vector.prototype.width attribute
Returns the first value of the vector
jQuery.Vector.prototype.x attribute
Returns the first value of the vector
jQuery.Vector.prototype.y attribute
Returns the 2nd value of the vector