CanJS - Utility functions

canjs

Overall description of the utility functions:

  1. can.isArray(obj): Check if an object is an array. can.isArray(object) returns true if the object is an explicitly an Array. If can.isArray is passed an array-like object, it will return false.
  2. can.isDeferred(subject): Check if an object is a Deferred. can.isDeferred returns true if an object is an instance of can.Deferred.
  3. can.isEmptyObject(obj): Check if an object has no properties.
  4. can.isFunction(obj): Check if obj is a function.
  5. can.makeArray(arrLike): Convert an array-like object to an Array.
  6. can.off.call(target, eventName, handler): Stop listening for events on an object.
  7. can.on.call(target, eventName, handler): Listen for events on an object.
  8. can.param(obj): Serialize an object into a query string.
  9. can.proxy(fn, context): Bind a function to its context.
  10. can.remode(nodeList): Remove elements from the DOM.
  11. can.sub(str, data, remove, s): Returns a string with {param} replaced values from data.
  12. can.underscore(str): Takes a CamelCase or mixedCase string and underscores the string on the capital letter.
  13. can.viewModel(el[, attr[, value]]): Read and write a component element's viewModel.

What is the purpose of the can.Object.same method?

Checks if two objects are the same. The signature for can.Object.same:

can.Object.same(a, b, compares, aParent, bParent, deep)
  • a and b: objects to be compared
  • compares: {Object}. An object that specifies how to compare properties. The keys of the compares object are names of properties in the objects to compare, and the values are functions that compare those properties. You can also pass 'i' to compare values as case-insensitive strings, or null not to compare the properties at all.

This function returns a boolean. This function does not work with objects that have circular references.

can.Object.same({name: "Justin"}, {name: "JUSTIN"}) //-> false

// ignore the name property
can.Object.same({name: "Brian"}, {name: "JUSTIN"}, {name: null}) //-> true

// ignore case
can.Object.same({name: "Justin"}, {name: "JUSTIN"}, {name: "i"}) //-> true

// deep rule
can.Object.same(
    { person : { name: "Justin" } },
    { person : { name: "JUSTIN" } },
    { person : { name: "i"      } }) //-> true

// supplied compare function
can.Object.same(
    {age: "Thirty"},
    {age: 30},
    {age: function( a, b ) {
        if( a == "Thirty" ) {
            a = 30
        }
        if( b == "Thirty" ) {
            b = 30
        }
        return a === b;
    }}
)      //-> true

What is the purpose of can.Object.subset?

Returns true if an Object is a subset of another Object. The signature of this function:

can.Object.subset(subset, set, compares)
  • subset: {Object}
  • set: {Object}
  • compares: {Object}. This is probably the same as that of the compares object used by can.Object.same

This function returns a boolean.

can.Object.subset({}, {foo: "bar"} ) //-> true

What is the purpose of the can.Object.subsets method?

Returns the sets in 'sets' that are a subset of checkSet. The signature of this function:

can.Object.subsets(checkSet, sets, compares)
can.Object.subsets(
    {userId: 20}, 
    [
        {userId: 20, limit: 30},
        {userId: 5},
        {}
    ]
); //-> [{userId: 20, limit: 30}]

What is the purpose of the can.addClass method?

Add a class to elements.

can.addClass(nodeList, className);

can.addClass( nodelist, className ) adds the specified class(es) to nodelist's HTMLElements. It does NOT replace any existing class(es) already defined.

can.addClass(can.$("#foo"),"bar");

// Add multiple classes:
can.addClass(can.$("#foo"),"bar man");

What is the purpose of the can.ajax method?

Make an AJAX request.

can.ajax(settings);

can.ajax( settings ) is used to make an asynchronous HTTP (AJAX) request similar to jQuery's ajax.

can.ajax({
    url: 'http://canjs.com/docs/can.ajax.html',
    success: function(document) {
        // ...
    }
});

What is the purpose of the can.append function?

Append content to elements.

can.append(nodeList, html);

can.append( wrappedNodeList, html ) inserts content to the end of each wrapped node list item(s) passed. This is a wrapper API for the underlying library being used. If you're using jQuery, this is a wrapper API for .append.

can.append(can.$('#demo'), 'Demos are fun!');

What is the purpose of can.batch?

can.batch.start( batchStopHandler ) and can.batch.stop( force, callStart ) are used to specify atomic operations. start prevents change events from being fired until stop is called.

can.batch.start();

player.removeAttr("tvshow");
player.attr("song", "What makes you beautiful");

can.batch.stop();

Why would we want to use can.batch?

Performance and correctness are the two most common reasons to use batch operations.

Sometimes, an object can temporarily be in an invalid state. For example, the previous player should have a tvshow or song property, but not both. Event listeners should never be called in an intermediate state. The can/map/define plugin uses can.batch.start and can.batch.stop to accomplish this when calling a setter.

import "can/map/define/"
var Player = can.Map.extend({
    define: {
        tvshow: {
            set: function(newValue) {
                this.removeAttr("song");
                return newValue;
            }
        },
        song: {
            set: function(newValue) {
                this.removeAttr("tvshow");
                return newValue;
            }
        }
    }
});

var player = new Player({ song: "Amish Paradise" });
player.bind("change", function(ev, attr, how, newVal, oldVal) {
    var song = this.attr("song");
    var tvshow = this.attr("tvshow");
    if(song) {
        console.log("The greatest song is " + song + ". TV is overrated.");
    }
    if(tvshow) {
        console.log("The greatest TV show is " + tvshow +
            ". Music is overrated.");
    }
});

player.attr("tvshow", "Breaking Bad");

Use can.batch.start and can.batch.stop to ensure that events are only triggered when a subject is in a valid state.

can.batch.start causes can.Map to begin an event batch. Until can.batch.stop is called, any events that would result from calls to attr are held back from firing. If you have lots of changes to make to can.Maps, batching them together can help performance especially if those can.Maps are live-bound to the DOM.

What is a batch number?

All events created within a set of start / stop calls share the same batchNum value. This can be used to respond only once for a given batchNum.

var batchNum;
obs.bind("change", function(ev, attr, how, newVal, oldVal) {
    if (!ev.batchNum || ev.batchNum !== batchNum) {
        batchNum = ev.batchNum;
        // your code here!
    }
});

What is the signature of can.batch.start?

can.batch.start([batchStopHandler])

The batchStopHandler is called after all the events have been fired

What is the signature of can.batch.stop?

End an event batch.

can.batch.stop([force[, callStart]])
  • force: boolean, default is false. Whether to stop batching events immediately
  • callStart: boolean, default is false. Whether to call can.batch.start after firing batched events.

can.batch.stop matches an earlier can.batch.start call. If can.batch.stop has been called as many times as can.batch.start (or if force is true), all batched events will be fired and any callbacks passed to can.batch.start since the beginning of the batch will be called. If _force and callStart are both true, a new batch will be started when all the events and callbacks have been fired.

What is the purpose of the can.batch.trigger function?

Trigger an event to be added to the current batch.

can.batch.trigger(item, event [, args])
  • item: {can.Map} the target of the event
  • event: {String | Object} the type of event, or an event object with a type given
  • args: {Array} the parameters to trigger the event with.

If events are currently being batched, calling can.batch.trigger adds an event to the batch. If events are not currently being batched, the event is triggered immediately.

What is the purpose of the can.trim function?

The can.trim function removes leading and trailing whitespace. It will also remove all newlines, spaces including non-breaking, and tabs. If these occur in the middle of the string, then they will be persisted.

can.trim(' foo '); // 'foo'

What is the purpose of the can.esc function?

The can.esc function escapes HTML code.

can.esc('<foo><bar>'); // '&lt;foo&gt;&&lt;bar&gt;'

What is can.getObject?

can.getObject looks up an object by path.

can.('foo.bar', [{foo: {bar: 'baz'}}]); // 'baz'

What is can.capitalize?

can.capitalize capitalizes a string.

can.capitalize('fooBar'); // 'FooBar'
can.capitalize('candy is fun!'); //-> Returns: 'Candy is fun!'

What is can.sub?

can.sub allows micro-templating.

can.sub('{greet}, world!', {greet: 'Hello'}); // 'Hello, world!'

What is can.deparam?

can.deparam transforms a form-encoded string into an object..

can.deparam('foo=bar&hello=world'); // {foo: 'bar', hello: 'world'}

What is can.makeArray?

can.makeArray converts array-like objects into real Arrays.

can.makeArray({0: 'foo', 1: 'bar', length: 2}); // ['foo', 'bar']

What is can.isArray?

can.isArray checks if an object is an Array.

can.isArray([]); // true

What is can.map?

can.map converts an array into another array using a callback.

can.map(['foo', 'bar'], function(element, index) {
    return el.toUppercase();
}); // ['FOO', 'BAR']

What is can.each?

can.each iterates through an array.

can.each([{prop: 'foo'}, {prop: 'bar'}], function(element, index) {
    // this callback will be called with:
    // element = {prop: 'foo'}, index = 0
    // element = {prop: 'bar'}, index = 1
});

What is can.extend?

can.extend extends one object with the properties of another.

var first = {},
second = {a: 'b', c: 'd'},
third = {c: 'e'};

var extended = can.extend(first, second, third);

extended === first; // true

first; // {a: 'b', c: 'e'}
second; // {a: 'b', c: 'd'}
third; // {c: 'e'}

can.extend merge the properties and values from the second and third (and subsequent objects) into the first object, and returns the first object.

What is can.param?

can.param turns an object into a query string.

can.param({a: 'b', c: 'd'}); // 'a=b&c=d'

What is can.isEmptyObject?

can.isEmptyObject checks whether an object is empty.

can.isEmptyObject({}); // true
can.isEmptyObject({foo: 'bar'}); // false

What is can.proxy?

can.proxy returns a function that calls another function with a set context.

var f = can.proxy(function(str) {
    return this.a + str;
}, {a: 'b'});
f('bar'); // 'bbar'

can.proxy takes two parameters. The first parameter is a function, and the second parameter is an object. can.proxy then returns a wrapper function, such that when the wrapper function is invoked with a parameter, that parameter is passed onto the original function, and the original function is invoked by the wrapper function in such a way that the object that was used as the second parameter to can.proxy is used as the this keyword inside the original function.

What is can.isFunction?

can.isFunction checks whether an object is a function.

can.isFunction({}); // false
can.isFunction(function() { }); // true

What is can.bind?

can.bind binds a callback to an event on an object.

// Binds handler on obj's eventName event.
can.bind(obj, eventName, handler);

What is can.unbind?

can.unbind unbinds a callback from an event on an object.

// Unbinds handler from obj's eventName event.
can.unbind(obj, eventName, handler);

What is can.delegate?

can.delegate binds a callback to an event on an all elements that match a selector.

// Binds handler on eventName events from all
// elements under obj that match selector.
can.delegate(obj, eventName, handler);

What is can.undelegate?

can.undelegate unbinds a callback from an event on an all elements that match a selector.

// Unbinds handler from eventName events from all
// elements under obj that match selector.
can.undelegate(obj, eventName, handler);

What is can.trigger?

can.trigger triggers an event on an object.

// Executes all handlers attached to obj for eventName
// with args as additional arguments.
can.trigger(obj, eventName, args);

What is can.ajax?

can.ajax will make an AJAX call and return a Deferred that resolves when the call has returned.

can.ajax({
    url: '/path/to/url',
    type: 'GET',
    async: true,
    dataType: 'json',
    success: function(json) { },
    error: function(xhr) { }
});

What is can.$?

can.$ creates a library-wrapped NodeList.

can.$(div.bar); // (in jQuery, a jQuery.fn object)

What is can.append?

can.append appends elements to the elements in a NodeList.

// Appends content to each element in nodelist.
can.append(nodelist, content);

What is the purpose of the can.buildFragment function?

Make a document fragment.

can.buildFragment(html, node)
  • html: {String} a string of HTML.
  • node: {DOM | Node} a node used to access a document to make the fragment with.

The can.buildFragment function return a document fragment made from html.

What is the purpose of the can.camelize function?

Capitalize the first letter after each hyphen in a string.

can.camelize('hello-world'); //-> Returns: 'helloWorld'

What is the purpose can.data?

Associate data with or retrieve data from DOM nodes.

can.data(nodeList, key, value) // store data in the DOM node
can.data(nodeList, key) // retrieve data from the DOM node
  • nodeList: {NodeList} The list of nodes to add this data to.
  • key: {String} The key to store this data under.
  • value: {*} The data to store.

Due to the way browsers security restrictions with plugins and external code, the data method cannot be used on object (unless it's a Flash plugin), applet or embed elements.

What is the purpose of the can.deparam function?

Takes a string of name value pairs and returns an object literal that represents those params.

can.deparam(params)
  • params: {String} A string like "foo=bar&person[age]=3"

The can.deparam function returns a JavaScript Object that represents the params.

What is the purpose of the can.each function?

Iterate through an array or object.

can.each(collection, callback)
  • collection: {Object} The object to iterate through.
  • callback: {function()} A function to call for each item in collection. callback will receive the item's value first and its key second.

can.each(collection, callback) iterates through an array or object like like jQuery.each.

can.each(
    [
        {prop: "val1"}, 
        {prop: "val2"}
    ],
    function( value, index ) {
        // function called with
        // index=0 value={prop: "val1"}
        // index=1 value={prop: "val2"}
    }
);

What is the purpose of the can.extend function?

Merge objects together.

can.extend(target, ...obj)
  1. target: {Object} The object to merge properties into.
  2. obj: {Object} The objects containing properties to merge.

The can.extend function returns an object, the target, post-merge. The can.extend(target, objectN) merges the contents of two or more objects together into the first object similarly to jQuery.extend.

var first = {},
second = {a: "b"},
third = {c: "d"};
can.extend(first, second, third); //-> first

first  //-> {a: "b", c: "d"}
second //-> {a: "b"}
third  //-> {c: "d"}

What is the purpose of the can.frag function?

Convert a String, HTMLElement, documentFragment, or contentArray into a documentFragment.

can.frag(item)
  1. item: {String | HTMLElement | documentFragment | contentArray}

The can.frag function returns a {documentFragment}. ContentArray's can be used to combine multiple HTMLElements into a single document fragment. For example:

var p = document.createElement("p");
p.innerHTML = "Welcome to <b>CanJS</b>";
var contentArray = ["<h1>Hi There</h1>", p];
var frag = can.frag( contentArray )

In the above code, contentArray contains 2 elements. The first element is a string, which is different from the string above it, and the second element is a DOM node create above. And frag will be a documentFragment with the following elements:

<h1>Hi There</h1>
<p>Wlecome to <b>CanJS</b></p>

What is the purpose of can.getObject?

Gets an object from a string.

can.getObject(name, roots, add)
  1. name: {String} the name of the object to look for
  2. roots: {Array} an array of root objects to look for the name. If roots is not provided, the window is used.
  3. add: {Boolean} true to add missing objects to the path. false to remove found properties. undefined to not modify the root object

Gets an object from a string. It can also modify objects on the 'object path' by removing or adding properties.

Foo = {Bar: {Zar: "Ted"}}
can.getObject("Foo.Bar.Zar") //-> "Ted"

What is the purpose of the can.hyphenate function?

Adds a hyphen before each uppercase letter and converts the entire string to lower case.

can.hyphenate('helloWorld'); //-> Returns: 'hello-world'

The can.hyphenate function returns the lowercase string with hyphens added before each letter that was uppercase in the source string.

What is the purpose of the can.import function?

Imports a module with the underlying module loader.

can.import(moduleName)
  1. moduleName: {String} The module name to load. Example: components/my-component.

The can.import function returns a promise that resolves if the module was successfully loaded and is rejected if the module can not be successfully loaded.

The can.import function is used internally by can.autorender when it finds <can-import> tags to import those modules before rendering the template.

<script type='text/stache' can-autorender>
    <can-import from="components/my-component">
    <my-component>
        {{message}}
    </my-compoennt>
</script>

In the above code, can.import will import "components/my-component" prior to the template being rendered.

The can.import function looks first for a System loader, followed by require.amd, followed by steal followed by a CommonJS require.

What is the purpose of the can.isArray function?

can.isArray(object) returns if the object is an explicitly an Array. If can.isArray is passed an array-like object, it will return false.

can.isArray([]);    // true
can.isArray([1, 2, 3]);    // true
can.isArray(can.makeArray({0: "foo", 1: "bar"})); // true
(function() { return can.isArray(arguments); })(); // false
can.isArray(document.querySelectorAll("p")); // false
can.isArray(true); // false

What is the purpose of the can.isDeferred function?

The can.isDeferred(subject) function returns true if an object is an instance of can.Deferred.

function convertDeferred(dfd) {
    return can.isDeferred(dfd) ? dfd : can.Deferred(dfd);
}

The above code use the can.isDeferred function, and the ternary operator to determine if the object dfd is already a can.Deferred object. If so, it returns the object as-is. If not, it invoke can.Deferred to create a deferred object.

What is the purpose of the can.isEmptyObject function?

Check if an object has no properties. can.isEmptyObject(obj) returns if an object has no properties similar to jQuery.isEmptyObject.

can.isEmptyObject({})      //-> true
can.isEmptyObject({a:"b"}) //-> false

What is the purpose of the can.isFunction function?

Check if an Object is a function. an.isFunction(object) returns if an object is a function similar to jQuery.isFunction.

can.isFunction({})           //-> false
can.isFunction(function(){}) //-> true

What is the purpose of the can.makeArray function?

Convert an array-like object to an Array.

can.makeArray({0 : "zero", 1: "one", length: 2}); // ["zero","one"]

What is the purpose of the can.param function?

Serialize an object into a query string like jQuery.param.

can.param({a: "b", c: "d"}) //-> "a=b&c=d"

What is the purpose of the can.proxy function?

Bind a function to its context.

can.proxy(fn, context)

The can.proxy function returns a function that calls fn in the context of the specified context. can.proxy(fn, context) accepts a function and returns a new one that will always have the context from which it was called. This works similar to jQuery.proxy.

var func = can.proxy(function(one){
    return this.a + one
}, {a: "b"});

func("two") //-> "btwo"

What is the purpose of the can.remove function?

Remove elements from the DOM. The can.remove( wrappedNodeList ) function removes the set of matched element(s) from the DOM.

What is the purpose of the can.sub function?

Returns a string with {param} replaced values from data.

can.sub(str, data, remove, s)
  1. str {String}: The string to make substitutes on.
  2. data {Object}: The data to be used to look for properties. If it's an array, multiple objects can be used.
  3. remove {Boolean}: if a match is found, remove the property from the object.
  4. s {String}: The string to replace.

The can.sub function returns the converted string or null if any data to render are undefined or null. The can.sub function returns a string with {param} replaced values from data, where param is the name of an object property.

can.sub("foo {bar}", {bar: "far"}) //-> "foo far"

What is the purpose of the can.underscore function?

Takes a CamelCase or mixedCase string and underscores the string on the capital letter. The can.underscore takes a CamelCase or mixedCase string and underscores the string on the capital letter. If parts of the string are not CamelCase or mixedCase, it will not change them. can.underscore will lower case the entire string as well.

can.underscore("OneTwo") //-> "one_two"
can.underscore("OneTwo threeFour") //-> "one_two three_four"

What is the purpose of the can.viewModel function?

Read and write a component element's viewModel.

can.viewModel(el[, attr[, value]])
  1. el {HTMLElement | NodeList}: can.Component element to get viewModel of.
  2. attr {String}: Attribute name to access.
  3. val {*}: Value to write to the viewModel attribute.

If only one argument, the can.viewModel function returns the viewModel itself. If two arguments are given, the can.viewModel function returns the attribute value. If three arguments are given, the can.viewModel function returns the element itself after assigning the value (for chaining).

The can.viewModel can be used to directly access a can.Component's viewModel. Depending on how it's called, it can be used to get the entire viewModel object, read a specific property from it, or write a property. The property read and write features can be seen as a shorthand for code such as:

$("my-thing").viewModel().attr("foo", val);

If using jQuery, this function is accessible as a jQuery plugin, with one fewer argument to the call:

$("my-element").viewModel("name", "Whatnot");
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License