Add behaviors to objects or static classes with mix
Using mix
YUI().use('node', function(Y) { // This method is in the core of the library, so we don't have to use() any // additional modules to access it. However, this example requires 'node'.
Adding functionality to individual objects
Static classes, such as DOM
, are implemented as object literals
with keys corresponding to public class methods. As such, static classes
aren't candidates for instantiation or prototype extension. To add
functionality to static classes, you need to work with the class's object
literal.
In this example, mix
is used to add a set of behaviors to a static class.
var Logging = function () { var logger = null; return { initLogger : function (logNode) { if (!logger) { logger = Y.one(logNode); } }, log : function (message) { if (logger) { logger.append('<p>' + message + '</p>'); } } } }(); var PageController = function () { var app_const = 12345; return { getConst : function () { return app_const; }, logConst : function () { this.initLogger('#demo_logger'); this.log('PageController class constant = ' + this.getConst() + ', logged courtesy of object augmentation via Y.mix.'); } }; }(); Y.mix(PageController, Logging); Y.on('click', PageController.logConst, '#demo_btn', PageController);
Much like augment
mix
works in similar fashion to augment
. In fact, augment
uses mix
under the hood. However, rather than adding functionality to class definitions (i.e. function prototypes), mix
can work with any object, including object literals and class instances.
See augment
and extend
for other techniques to help manage your code structure.