jquery.lang.helper-api

来源:互联网 发布:沉迷网络 大学生 事例 编辑:程序博客网 时间:2024/06/18 06:13

Language Helpers  page     

Source

JavaScriptMVC has several lightweight language helper plugins.

Object

Methods useful for comparing Objects. For example, if two objects are thesame:

$.Object.same({foo: "bar"}, {foo: "bar"});

Observe

Makes an Object's properties observable:

var person = new $.Observe({ name: "Justin" })

person.bind('change', function(){ ... })

person.attr('name', "Brian");

String

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"}})

toJSON

Used to create or consume JSON strings.

Vector

Used for vector math.

jQuery.Object  class     

Source

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     

Source

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:

  • 'i' - ignores case
  • null - ignores this property

aParent {}

bParent {}

deep {optional:Object}

used internally

returns {undefined}

jQuery.Object.subset  function     

Source

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     

Source

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

Source

Observe provides the awesome observable pattern for JavaScript Objects andArrays. It lets you

  • Set and remove property or property values on objects and arrays
  • Listen for changes in objects and arrays
  • Work with nested properties

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, which is used for objects like: {foo: 'bar'}, and
  • $.Observe.List, which is used for arrays like ['foo','bar']

$.Observe.List and $.Observe are very similar. In fact, $.Observe.Listinherits $.Observe and only adds a few extra methods for manipulating arrayslikepush.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:

  • bind - listen for any type of change
  • delegate - listen to a specific type of change

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

Source

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    

Source

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    

Source

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    

Source

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    

Source

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    

Source

Returns the serialized form of this list.

API

observe.list.serialize() ->undefined

returns {undefined}

jQuery.Observe.List.prototype.shift  function    

Source

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

jQuery.Observe.List.prototype.splice  function     

Source

Remove items or add items from a specific point in thelist.

Example

The following creates a list of numbers and replaces 2 and3 with "a", and "b".

var l = 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:

  • attr - "1" - indicates where the remove event took place
  • how - "remove"
  • newVals - undefined
  • oldVals - [1,2] -the array of removed values
  • where - 1 - the location of where these items where removed

The second change event is the addition of the"a", and "b" values where the callback values will be:

  • attr - "1" - indicates where the add event took place
  • how - "added"
  • newVals - ["a","b"]
  • oldVals - [1, 2] - the array of removed values
  • where - 1 - the location of where these items where added

API

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    

Source

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     

Source

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     

Source

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     

Source

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:

  • add - a attribute is added
  • set - an existing attribute's value is changed
  • remove - an attribute is removed

The change event is fired with:

  • the attribute changed
  • how it was changed
  • the newValue of the attribute
  • the oldValue of the attribute

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, usejQuery.Observe.prototype.delegate.

handler(event, attr, how, newVal, oldVal) {Function}

A callback function where

  • event - the event
  • attr - the name of the attribute changed
  • how - how the attribute was changed (add, set, remove)
  • newVal - the new value of the attribute
  • oldVal - the old value of the attribute

·        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 inbindand 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 tojQuery.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     

Source

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}

  • the type of event with any optional namespaces. Currently, only change events are supported with bind.

handler {optional:Function}

  • The original handler function passed to bind.

returns {jQuery.Observe}

the original observe for chaining.

jQuery.Observe.prototype.undelegate  function    

plugin: jquery/lang/observe/delegate

Source

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     

Source

A collection of useful string helpers. Available helpers are:

  • capitalize: Capitalizes a string (some_string » Some_string)
  • camelize: Capitalizes a string from something undercored (some_string » someString, some-string » someString)
  • classize: Likecamelize, but the first part is also capitalized (some_string » SomeString)
  • niceName: Likeclassize, but a space separates each 'word' (some_string » Some String)
  • underscore: Underscores a string (SomeString » some_string)
  • sub: Returns a string with {param} replaced values from data.

·              $.String.sub("foo {bar}",{bar:"far"})

      //-> "foofar"

jQuery.String.camelize  function     

Source

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     

Source

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     

Source

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     

Source

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     

Source

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     

Source

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     

Source

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     

Source

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     

Source

Underscores a string.

jQuery.String.underscore("OneTwo") //->"one_two"

API

$.String.underscore(s) ->String

s {String}

returns {String}

the underscored string

jQuery.toJSON  page     

Source

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     

Source

Evaluates a given piece of json source.

Evaluates a given piece of json source.

API

$.evalJSON(src) -> undefined

src {}

returns {undefined}

jQuery.quoteString  function     

Source

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     

Source

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     

Source

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     

Source

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     

Source

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     

Source

Returns the 2nd value of the vector

jQuery.Vector.prototype.left  attribute     

Source

same as x()

jQuery.Vector.prototype.minus  function     

Source

Like plus but subtracts 2 vectors

API

vector.minus() -> jQuery.Vector

returns {jQuery.Vector}

jQuery.Vector.prototype.plus  function     

Source

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     

Source

Same as y()

jQuery.Vector.prototype.toString  function     

Source

returns (x,y)

API

vector.toString() -> String

returns {String}

jQuery.Vector.prototype.update  function     

Source

Replaces the vectors contents

API

vector.update(array) ->undefined

array {Object}

returns {undefined}

jQuery.Vector.prototype.width  attribute     

Source

Returns the first value of the vector

jQuery.Vector.prototype.x  attribute     

Source

Returns the first value of the vector

jQuery.Vector.prototype.y  attribute     

Source

Returns the 2nd value of the vector