Package Exports
- can-util
- can-util/dom/ajax/ajax
- can-util/dom/attr/attr
- can-util/dom/child-nodes/child-nodes
- can-util/dom/class-name/class-name
- can-util/dom/contains/contains
- can-util/dom/data/core
- can-util/dom/data/data
- can-util/dom/dispatch/dispatch
- can-util/dom/document/document
- can-util/dom/dom
- can-util/dom/events/attributes/attributes
- can-util/dom/events/delegate/delegate
- can-util/dom/events/delegate/enter-leave
- can-util/dom/events/events
- can-util/dom/events/inserted/inserted
- can-util/dom/events/make-mutation-event/make-mutation-event
- can-util/dom/events/removed/removed
- can-util/dom/frag/frag
- can-util/dom/fragment/fragment
- can-util/dom/is-of-global-document/is-of-global-document
- can-util/dom/location/location
- can-util/dom/matches/matches
- can-util/dom/mutate/mutate
- can-util/dom/mutation-observer/document/document
- can-util/dom/mutation-observer/mutation-observer
- can-util/js/assign/assign
- can-util/js/base-url/base-url
- can-util/js/cid-map/cid-map
- can-util/js/cid-set/cid-set
- can-util/js/cid/cid
- can-util/js/cid/get-cid
- can-util/js/deep-assign/deep-assign
- can-util/js/defaults/defaults
- can-util/js/deparam/deparam
- can-util/js/dev/dev
- can-util/js/diff-object/diff-object
- can-util/js/diff/diff
- can-util/js/each/each
- can-util/js/get/get
- can-util/js/global/global
- can-util/js/import/import
- can-util/js/is-array-like/is-array-like
- can-util/js/is-array/is-array
- can-util/js/is-browser-window/is-browser-window
- can-util/js/is-container/is-container
- can-util/js/is-empty-object/is-empty-object
- can-util/js/is-function/is-function
- can-util/js/is-iterable/is-iterable
- can-util/js/is-node/is-node
- can-util/js/is-plain-object/is-plain-object
- can-util/js/is-promise-like/is-promise-like
- can-util/js/is-promise/is-promise
- can-util/js/is-string/is-string
- can-util/js/is-web-worker/is-web-worker
- can-util/js/join-uris/join-uris
- can-util/js/js
- can-util/js/last/last
- can-util/js/log/log
- can-util/js/make-array/make-array
- can-util/js/make-map/make-map
- can-util/js/make-promise/make-promise
- can-util/js/omit/omit
- can-util/js/param/param
- can-util/js/parse-uri/parse-uri
- can-util/js/set-immediate/set-immediate
- can-util/js/single-reference/single-reference
- can-util/js/string-to-any/string-to-any
- can-util/js/string/string
- can-util/js/tests
- can-util/js/types/types
- can-util/namespace
- can-util/test/test
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (can-util) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
can-util
Common utilities for CanJS projects
- can-util/dom Object- can-util/dom/ajax/ajax function
- can-util/dom/child-nodes/child-nodes function
- can-util/dom/class-name/class-name Object
- can-util/dom/data/data Object
- can-util/dom/dispatch/dispatch function
- can-util/dom/document/document function
- can-util/dom/events/events Object
- can-util/dom/frag/frag function
- can-util/dom/mutate/mutate Object
 
- can-util/js Object-- can-util/js/assign/assign function-- assign(target, source)-- can-util/js/base-url/base-url function-- baseUrl(optionalBaseUrlToSet)-- can-util/js/cid/cid function-- cid(object, optionalObjectType)-- can-util/js/deep-assign/deep-assign function-- deepAssign(target, [ ... sources ])-- can-util/js/deparam/deparam function-- deparam(params)-- can-util/js/diff/diff function-- diff(oldList, newList)-- can-util/js/diff-object/diff-object function-- diffObject(oldObject, newObject)-- can-util/js/each/each function-- each(elements, callback, context)-- can-util/js/global/global function-- GLOBAL()-- can-util/js/import/import function-- importModule(moduleName, parentName)-- can-util/js/is-array-like/is-array-like function-- isArrayLike(obj)-- can-util/js/is-browser-window/is-browser-window function-- isBrowserWindow()-- can-util/js/is-empty-object/is-empty-object function-- isEmptyObject(obj)- can-util/js/is-function/is-function -- can-util/js/is-node/is-node function-- isNode()-- can-util/js/is-plain-object/is-plain-object function-- isPlainObject(obj)-- can-util/js/is-promise/is-promise function-- isPromise(obj)-- can-util/js/is-string/is-string function-- isString(obj)-- can-util/js/is-web-worker/is-web-worker function-- isWebWorker()-- can-util/js/join-uris/join-uris function-- joinURIs(base, href)-- can-util/js/make-array/make-array function-- makeArray(arr)-- can-util/js/param/param function-- param(params)
API
dom {Object}
A collection of modules that operate on DOM.
Object
can-util/dom/ajax/ajax function
ajax(settings)
- settings {Object}: Configuration options for the AJAX request. The list of configuration options is the same as for jQuery.ajax.
- returns {Promise}: A Promise that resolves to the data.
can-util/dom/child-nodes/child-nodes function
childNodes(node)
Get all of the childNodes of a given node.
var stache = require("can-stache");
var childNodes = require("can-util/child-nodes/child-nodes");
var html = "<div><h1><span></span></h1></div>";
var frag = stache(html)();
console.log(childNodes(frag)[0].nodeName); // -> DIV- node {Object}: The Node that you want child nodes for.
className {Object}
Allows querying and manipulation of classes on HTML elements
var className = require("can-util/dom/class-name/class-name");
var fooDiv = document.createElement("div");
className.add(fooDiv, "foo");
fooDiv.outerHTML; //-> '<div class="foo"></div>'Object
className.add.call(el, cls)
Add a class name to a DOM node if it is not already there.
className.add.call(el, "container");- className {String}: A string representing a single class name token
- returns {void}:
className.has.call(el, cls)
Determine wheter a DOM node has a given class name.
var isContainer = className.has.call(el, "container");- className {String}: A string representing a single class name token
- returns {Boolean}: true if the element's class attribute contains the token, false otherwise.
className.remove.call(el, cls)
Remove a class name from a DOM node if it exists on the node
className.remove.call(el, "container");- className {String}: A string representing a single class name token
- returns {void}:
data {Object}
Allows associating data as a key/value pair for a particular DOM Node.
var domData = require("can-util/dom/data/data");Object
domData.cid.call(el)
- returns - {Number}: The value of the element's unique CID- Set a unique identifier for the dom node, using the undefined property. 
domData.clean.call(el, key)
Remove data from an element previously added by set
domData.clean.call(el, "metadata");domData.get.call(el, key)
Get data that was stored in a DOM Node using the specified key.
var metadata = domData.get.call(el, "metadata");- key {String}: A string used as a unique key for storing data associated with this DOM Node.
domData.getCid.call(el)
- returns - {Number}: The value of the element's unique CID- Return the previously set unique identifier for the dom node. 
domData.set.call(el, key, value)
- name {String}: the key to store the value under
- value {*}: the value to store under the key
  Set data to be associated with a DOM Node using the specified key. If data already exists for this key, it will be overwritten.
domData.set.call(el, "metadata", {
  foo: "bar"
});can-util/dom/dispatch/dispatch function
dispatch.call(el, event, args, bubbles)
Dispatch an event on an element.
- event {Object|String}: An object specifies options applied to this event.
- args {Array}: Arguments passed into this event.
- bubbles {Boolean}: Specifies whether this event should bubble (by default it will).
can-util/dom/document/document function
document(document)
- document {Object}: An optional document-like object to set as the context's document
Optionally sets, and returns, the document object for the context.
var documentShim = { getElementById() {...} };
var domDocument = require("can-util/dom/data/data");
domDocument(documentShim);
...
domDocument().getElementById("foo");events {Object}
Allows you to listen to a domEvent and special domEvents.
var domEvents = require("can-util/dom/events/events");Object
attributes {events}
Adds a listenable "attributes" event to DOM nodes, which fires when the node's attributes change.
events
delegateEvents {events}
Add delegate listeners to DOM events. Delegated listeners use a selector on an ancestor element to determine when to fire the event for an item. This can help cases where large numbers of similar DOM nodes are added into a DOM subtree, since event handlers do not have to be attached to each new node.
events
inserted {events}
This event fires when nodes are added as descendants of the attached element
events
can-util/dom/events/make-mutation-event/make-mutation-event function
makeMutationEvent(specialEventNae, mutationNodesProperty)
- specialEventName {String}: the event to handle as a mutation observer-based event
- mutationNodesProperty {String}: the property of interest in a DOM mutation
This function provides a simple interface to bind the DOM events interface to the mutation observer interface, by firing an event when a matching mutation is generated by the client
removed {events}
This event fires when descendant elements of the bound element are detached or destroyed.
events
can-util/dom/frag/frag function
Convert a String, HTMLElement, documentFragment, or contentArray into a documentFragment.
frag: function(item, doc)
- item - {String|HTMLElement|documentFragment|contentArray}:
- doc - {Document}: an optional DOM document in which to build the fragment
- returns {documentFragment}:
mutate {Object}
Mutate an element by appending, inserting, and removing DOM nodes. Use this so that on the server "inserted" will be fired.
var mutate = require("can-util/dom/mutate/mutate");
var el = document.createElement("div");
el.addEventListener("inserted", function(){
  console.log("Inserted was fired!");
});
mutate.appendChild.call(document.body, el);Object
mutate.appendChild.call(el, child)
Used to append a node to an element and trigger the "inserted" event on all of the newly inserted children. Since mutated takes an array we convert the child to an array, or in the case of a DocumentFragment we first convert the childNodes to an array and call inserted on those.
mutate.insertBefore.call(el, ref, child)
Like mutate.appendChild, used to insert a node to an element before a reference node and then trigger the "inserted" event.
mutate.removeChild.call(el, child)
Like mutate.appendChild, used to insert a node to an element before a reference node and then trigger the "removed" event.
mutate.replaceChild.call(el, child)
Like mutate.appendChild and mutate.removeChild, used to replace a node with another node and trigger "removed" on the removed element and "inserted" on the inserted elements.
js {Object}
Utilities for manipulating JavaScript data structures.
Object
can-util/js/assign/assign function
assign(target, source)
A simplified version of Object.assign, which only accepts a single source argument.
var assign = require("can-util/js/assign/assign");
var obj = {};
assign(obj, {
  foo: "bar"
});
console.log(obj.foo); // -> "bar"- target {Object}: The destination object. This object's properties will be mutated based on the object provided assource.
- source {Object}: The source object whose own properties will be applied totarget.
- returns {Object}: Returns thetargetargument.
can-util/js/base-url/base-url function
baseUrl(optionalBaseUrlToSet)
Get and/or set the "base" (containing path) of the document.
var baseUrl = require("can-util/js/base-url/base-url");
console.log(baseUrl());           // -> "http://localhost:8080"
console.log(baseUrl(baseUrl() + "/foo/bar")); // -> "http://localhost:8080/foo/bar"
console.log(baseUrl());           // -> "http://localhost:8080/foo/bar"- setUrl {String}: An optional base url to override reading the base URL from the known path.
- returns {String}: Returns the set or computed base URL
can-util/js/cid/cid function
cid(object, optionalObjectType)
Get a unique identifier for the object, optionally prefixed by a type name.
Once set, the unique identifier does not change, even if the type name changes on subsequent calls.
var cid = require("can-util/js/cid/cid");
var x = {};
var y = {};
console.log(cid(x, "demo")); // -> "demo1"
console.log(cid(x, "prod")); // -> "demo1"
console.log(cid(y));         // -> "2"- object {Object}: The object to uniquely identify.
- name {String}: An optional type name with which to prefix the identifier
- returns {String}: Returns the unique identifier
can-util/js/deep-assign/deep-assign function
deepAssign(target, [ ... sources ])
Assign properties from a source object to a target object, deeply copying properties that are objects or arrays.
var deepAssign = require("can-util/js/deep-assign/deep-assign");
var dest = deepAssign({}, {
  obj: {
        foo: "bar"
    }
}, {
  arr: [{ hello: "world" }]
});
console.log(dest.obj.foo); // -> "bar"- target {Object}: The target object who's properties will be assigned from the source objects.
- source {Object}: Source objects from which properties will be assigned to thetargetobject. Sources will be copied deeply; meaning any object or array properties will be traversed and copied (like a clone).
can-util/js/deparam/deparam function
deparam(params)
- params {String}: a form-urlencoded string of key-value pairs
- returns - {Object}: The params formatted into an object- Takes a string of name value pairs and returns a Object literal that represents those params. - var deparam = require("can-util/js/deparam/deparam"); console.log(JSON.stringify(deparam("?foo=bar&number=1234"))); // -> '{"foo" : "bar", "number": 1234}' console.log(JSON.stringify(deparam("#foo[]=bar&foo[]=baz"))); // -> '{"foo" : ["bar", "baz"]}' console.log(JSON.stringify(deparam("foo=bar%20%26%20baz"))); // -> '{"foo" : "bar & baz"}' 
can-util/js/diff/diff function
diff(oldList, newList)
- oldList {ArrayLike}: the array to diff from
- newList {ArrayLike}: the array to diff to
- returns - {Array}: a list of Patch objects representing the differences- Returns the difference between two ArrayLike objects (that have nonnegative integer keys and the - lengthproperty) as an array of patch objects.- A patch object returned by this function has the following properties: - index: the index of newList where the patch begins
- deleteCount: the number of items deleted from that index in newList
- insert: an Array of items newly inserted at that index in newList
 - var diff = require("can-util/js/diff/diff"); console.log(diff([1], [1, 2])); // -> [{index: 1, deleteCount: 0, insert: [2]}] console.log(diff([1, 2], [1])); // -> [{index: 1, deleteCount: 1, insert: []}] 
can-util/js/diff-object/diff-object function
diffObject(oldObject, newObject)
- oldObject {Object}: the object to diff from
- newObject {Object}: the object to diff to
- returns - {Array}: an array of object-patch objects- Find the differences between two objects, based on properties and values - The object-patch object format has the following keys: - property: the property key on the new object
- type: the type of operation on this property: add, remove, or set
- value: the new value (if type is "add" or "set")
 - var diffObject = require("can-util/js/diff-object/diff-object"); console.log(diffObject({a: 1, b: 2}, {b: 3, c: 4})); // -> [{property: "a", type: "remove"}, {property: "b", type: "set": value: 3}, {property: "c", type: "add", "value": 4}] 
can-util/js/each/each function
each(elements, callback, context)
Loop over each element in an Array-Like data structure.
- elements - {Object|ArrayLike}:
- callback - {function(element, key, elements)}:
- context - {Object}: the context object
- returns - {ArrayLike}: the orignal array of elements- var each = require("can-util/js/each/each"); each([2,1,0], function(i) { console.log(this[i]); }, [4,5,6]); // -> 6 \n 5 \n 4 
can-util/js/global/global function
GLOBAL()
Returns the global that this environment provides. It will be one of:
- Browser: window
- Web Worker: self
- Node.js: global
var GLOBAL = require("can-util/js/global/global");
var g = GLOBAL();
// In a browser
console.log(g === window); // -> true- returns {Object}: The global object for this JavaScript environment.
can-util/js/import/import function
importModule(moduleName, parentName)
var importModule = require("can-util/js/import/import");
importModule("foo.stache").then(function(){
  // module was imported
});- moduleName {String}: The module to be imported.
- parentName {String}: A parent module that will be used as a reference for resolving relative module imports.
- returns {Promise}: A Promise that will resolve when the module has been imported.
can-util/js/is-array-like/is-array-like function
isArrayLike(obj)
Determines if an object is "array like", meaning it can be looped over. Any object with a .length property is array like.
var isArrayLike = require("can-util/js/is-array-like/is-array-like");
// Arrays
console.log(isArrayLike([{ foo: "bar" }])); // -> true
// Strings
console.log(isArrayLike("some string")); // -> true
// Objects with .length property
console.log(isArrayLike({ length: 11 })); // -> true
// Numbers and Booleans are not.
console.log(isArrayLike(true)); // -> false
console.log(isArrayLike(13)); // -> false- obj {*}: Any object type.
- returns {Boolean}: True, if the object is similar to an array.
can-util/js/is-browser-window/is-browser-window function
isBrowserWindow()
Returns true if the code is running within a Browser window. Use this function if you need special code paths for when running in a Browser window, a Web Worker, or another environment (such as Node.js).
var isBrowserWindow = require("can-util/js/is-browser-window/is-browser-window");
var GLOBAL = require("can-util/js/global/global");
if(isBrowserWindow()) {
  console.log(GLOBAL() === window); // -> true
}- returns {Boolean}: True if the environment is a Browser window.
can-util/js/is-empty-object/is-empty-object function
isEmptyObject(obj)
Used to determine if an object is an empty object (an object with no enumerable properties) such as {}.
var isEmptyObject = require("can-util/js/is-empty-object/is-empty-object");
console.log(isEmptyObject({})); // -> true
console.log(isEmptyObject({ a: 1 })); // -> false
var obj = {};
Object.defineProperty(obj, "foo", {
    enumerable: false,
    value: "bar"
});
console.log(isEmptyObject(obj)); // -> true- obj {Object}: Any object.
- returns {Boolean}: True if the object is an object with no enumerable properties.
can-util/js/is-node/is-node function
Determines if your code is running in Node.js.
isNode()
var isNode = require("can-util/js/is-node/is-node");
var GLOBAL = require("can-util/js/global/global");
if(isNode()) {
  console.log(GLOBAL() === global); // -> true
}- returns {Boolean}: True if running in Node.js
can-util/js/is-plain-object/is-plain-object function
isPlainObject(obj)
Attempts to determine if an object is a plain object like those you would create using the curly braces syntax: {}. The following are not plain objects:
- Objects with prototypes (created using the newkeyword).
- Booleans.
- Numbers.
- NaN.
var isPlainObject = require("can-util/js/is-plain-object/is-plain-object");
// Created with {}
console.log(isPlainObject({})); // -> true
// new Object
console.log(isPlainObject(new Object())); // -> true
// Custom object
var Ctr = function(){};
var obj = new Ctr();
console.log(isPlainObject(obj)); // -> false- obj {Object}:
- returns {Boolean}:
can-util/js/is-promise/is-promise function
isPromise(obj)
Determines if an object is a Promise.
var isPromise = require("can-util/js/is-promise/is-promise");
var promise = new Promise(function(resolve){
  resolve();
});
console.log(isPromise(promise)); // -> true
console.log(isPromise("foo bar")); // -> false- obj {Object}: An object to be tested.
- returns {Boolean}: True if the object is a Promise.
can-util/js/is-string/is-string function
Determines if the provided argument is a string.
isString(obj)
var isString = require("can-util/js/is-string/is-string");
console.log(isString("foo")); // -> true
console.log(isString(String("foo")); // -> true
console.log(isString({})); // -> false- obj {*}: An object to test if is a string.
- returns {Boolean}: True if the object is a string.
can-util/js/is-web-worker/is-web-worker function
Determines if the code is running with a Web Worker.
isWebWorker()
var isWebWorker = require("can-util/js/is-web-worker/is-web-worker");
var GLOBAL = require("can-util/js/global/global");
if(isWebWorker()) {
  console.log(GLOBAL() === self); // -> true
}- returns {Boolean}: True if running in a Web Worker.
can-util/js/join-uris/join-uris function
Join together a URI path to a base.
joinURIs(base, href)
Provides a convenient way to join together URIs handling relative paths.
var joinURIs = require("can-util/js/join-uris");
var base = "http://example.com/some/long/path";
var href = "../../images/foo.png";
var res = joinURIs(base, href);
console.log(res); // -> http://example.com/images/foo.png- base - {String}:
- href - {String}:
- returns {String}: The result of joining the two parts.
can-util/js/make-array/make-array function
makeArray(arr)
- arr {ArrayLike}: any array-like object
- returns - {Array}: a JavaScript array object with the same elements as the passed-in ArrayLike- makeArray takes any array-like object (can-list, NodeList, etc.) and converts it to a JavaScript array 
can-util/js/param/param function
Serialize an object into a query string.
param(params)
  Serializes an object or array into a query string useful for making Ajax requests or the
  browser. param handles nested objects and arrays.  It uses encodeURIComponent to
  escape values and keys.
param({a: "b", c: "d"}) //-> "a=b&c=d"
param({a: ["X","Y"]})   //-> "a[]=X&a[]=Y"- params {Object}: [description]
- returns {String}: [description]
can-util/js/set-immediate/set-immediate module
setImmediate(function())
- cb {function}:
Polyfill for setImmediate() if it doesn't exist in the global context
string {Object}
String utilities used by CanJS libraries
Object
string.esc(content)
- content {String}: a string
- returns {String}: the string safely HTML-escaped
string.getObject(name, roots, add)
- name {String}: a String of dot-separated keys, representing a path of properties
- roots {Object|Array}: the object to use as the root for property based navigation
- add {Boolean}: if true, add the parts at each step as new objects
- returns - {*}: the value at the property path descending from- roots- Return the result of descending the path - namethrough the properties of the object or objects- roots- If - rootsis an Array, each element of the array is evaluated, in order, until the path is found in an element's properties (and properties-of-properties, etc.). Otherwise- rootsis evaluated as the root object, returning either the object at the property path descended from- rootsor- undefinedif any subpath is not found.- A path is a dot-delimited sequence of zero or more property names, such that "foo.bar" means "the property 'bar' of the object at the property 'foo' of the root." An empty path returns the first object in - rootsif it's an array,- rootsitself otherwise.- If - addis- trueand- pathis not found in any roots, a matching path that resolves to an empty object is added to the first object in- rootsif- rootsis an array,- rootsitself otherwise.- var string = require("can-util/js/string/string"); console.log(string.getObject("a.b.c", {a: {b: {c: "foo"}}})); // -> "foo" console.log(string.getObject("a.b.c", {a: {}})); // -> undefined console.log(string.getObject("a.b", [{a: {}}, {a: {b: "bar"}}])); // -> "bar" 
string.capitalize(s)
- s {String}: the string to capitalize
- returns - {String}: the supplied string with the first character uppercased if it is a letter- var string = require("can-util/js/string/string"); console.log(string.capitalize("foo")); // -> "Foo" console.log(string.capitalize("123")); // -> "123" 
string.camelize(s)
- str {String}: the string to camelCase
- returns - {String}: the supplied string with hyphens removed and following letters capitalized.- var string = require("can-util/js/string/string"); console.log(string.camelize("foo-bar")); // -> "fooBar" console.log(string.camelize("-webkit-flex-flow")); // -> "WebkitFlexFlow" 
string.hyphenate(s)
- str {String}: a string in camelCase
- returns - {String}: the supplied string with camelCase converted to hyphen-lowercase digraphs- var string = require("can-util/js/string/string"); console.log(string.hyphenate("fooBar")); // -> "foo-bar" console.log(string.hyphenate("WebkitFlexFlow")); // -> "Webkit-flex-flow" 
string.underscore(s)
- str {String}: a string in camelCase
- returns - {String}: the supplied string with camelCase converted to underscore-lowercase digraphs- var string = require("can-util/js/string/string"); console.log(string.underscore("fooBar")); // -> "foo_bar" console.log(string.underscore("HTMLElement")); // -> "html_element" 
string.sub(str, data, remove)
- str {String}: a string with {curly brace} delimited property names
- data {Object}: an object from which to read properties
- returns - {String|null}: the supplied string with delimited properties replaced with their values if all properties exist on the object, null otherwise If- removeis true, the properties found in delimiters in- strare removed from- data.- var string = require("can-util/js/string/string"); console.log(string.sub("foo_{bar}", {bar: "baz"}})); // -> "foo_baz" console.log(string.sub("foo_{bar}", {})); // -> null 
can-util/js/string-to-any/string-to-any function
Turns a string representation of a primitive type back into the associated primitive.
stringToAny(string)
Examines the provided string to see if it can be converted to a primitive type. Supported arguments are:
stringToAny("NaN"); // -> NaN
stringToAny("44.4"); // -> 44.4
stringToAny("false"); // -> false- string {String}: A string to convert back to its primitive type.
- returns {*}: The primitive representation of the provided string.
Contributing
Making a Build
To make a build of the distributables into dist/ in the cloned repository run
npm install
node buildRunning the tests
Tests can run in the browser by opening a webserver and visiting the test.html page.
Automated tests that run the tests from the command line in Firefox can be run with
npm test