From a2ed02ca012505c8c6fb92c3db8681290b370320 Mon Sep 17 00:00:00 2001 From: Adam Shaw Date: Sun, 10 Jul 2016 13:11:24 -0700 Subject: [PATCH] Calendar options binding/triggering system --- lumbar.json | 1 + src/Calendar.options.js | 62 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 src/Calendar.options.js diff --git a/lumbar.json b/lumbar.json index 71561e8a7f..58d0e5d690 100644 --- a/lumbar.json +++ b/lumbar.json @@ -38,6 +38,7 @@ "src/common/View.js", "src/common/Scroller.js", "src/Calendar.js", + "src/Calendar.options.js", "src/defaults.js", "src/lang.js", "src/Header.js", diff --git a/src/Calendar.options.js b/src/Calendar.options.js new file mode 100644 index 0000000000..6fc31f2452 --- /dev/null +++ b/src/Calendar.options.js @@ -0,0 +1,62 @@ +/* +Options binding/triggering system. +*/ +Calendar.mixin({ + + // A map of option names to arrays of handler objects. Initialized to {} in Calendar. + // Format for a handler object: + // { + // func // callback function to be called upon change + // names // option names whose values should be given to func + // } + optionHandlers: null, + + // Calls handlerFunc immediately, and when the given option has changed. + // handlerFunc will be given the option value. + bindOption: function(optionName, handlerFunc) { + this.bindOptions([ optionName ], handlerFunc); + }, + + // Calls handlerFunc immediately, and when any of the given options change. + // handlerFunc will be given each option value as ordered function arguments. + bindOptions: function(optionNames, handlerFunc) { + var handlerObj = { func: handlerFunc, names: optionNames }; + var i; + + for (i = 0; i < optionNames.length; i++) { + this.registerOptionHandlerObj(optionNames[i], handlerObj); + } + + this.triggerOptionHandlerObj(handlerObj); + }, + + // Puts the given handler object into the internal hash + registerOptionHandlerObj: function(optionName, handlerObj) { + (this.optionHandlers[optionName] || (this.optionHandlers[optionName] = [])) + .push(handlerObj); + }, + + // Reports that the given option has changed, and calls all appropriate handlers. + triggerOptionHandlers: function(optionName) { + var handlerObjs = this.optionHandlers[optionName] || []; + var i; + + for (i = 0; i < handlerObjs.length; i++) { + this.triggerOptionHandlerObj(handlerObjs[i]); + } + }, + + // Calls the callback for a specific handler object, passing in the appropriate arguments. + triggerOptionHandlerObj: function(handlerObj) { + var optionNames = handlerObj.names; + var optionValues = []; + var i; + + for (i = 0; i < optionNames.length; i++) { + optionValues.push(this.options[optionNames[i]]); + } + + handlerObj.func.apply(this, optionValues); // maintain the Calendar's `this` context + } + +});