This section provides some useful examples for how you might use application-level JavaScript modules.
This first example adds a reusable Knockout custom binding that can be used across widgets:
define( //------------------------------------------------------------------- // DEPENDENCIES //------------------------------------------------------------------- ['jquery', 'knockout', 'ccLogger'], //------------------------------------------------------------------- // Module definition //------------------------------------------------------------------- function($, ko, CCLogger) { 'use strict'; // A simple binding that highlights an element when it loses focus. ko.bindingHandlers.highlight_on_blur = { init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { $(element).on('blur.demo.ko', function() { $(this).css('background-color','yellow'); }); $(element).on('focus.demo.ko', function() { $(this).css('background-color','white'); }); } }; return { onLoad : function() { CCLogger.info("Loading Demo KO Bindings"); } }; } );
This example demonstrates how to create an application-level module with reusable methods or view models:
define( //------------------------------------------------------------------- // DEPENDENCIES //------------------------------------------------------------------- ['jquery', 'knockout', 'ccLogger'], //------------------------------------------------------------------- // Module definition //------------------------------------------------------------------- function($, ko, CCLogger) { 'use strict'; return { onLoad : function() { CCLogger.info("Loading Demo Shared View Models"); }, doMessage : function() { alert("Shared View Models"); }, viewModel : ko.observable({ firstName : ko.observable('Bob'), surname : ko.observable('Test') }) }; } );