diff --git a/misc/states.js b/misc/states.js index 6d98da8..f82ab42 100644 --- a/misc/states.js +++ b/misc/states.js @@ -52,6 +52,8 @@ states.Dependent = function (args) { for (var selector in this.dependees) { this.initializeDependee(selector, this.dependees[selector]); } + // Reevaluate to execute initial states. + this.reevaluate(); }; /** @@ -106,12 +108,18 @@ states.Dependent.prototype = { this.values[selector][state.name] = null; // Monitor state changes of the specified state for this dependee. - $(selector).bind('state:' + state, $.proxy(function (e) { + $dependee = $(selector); + $dependee.bind('state:' + state, $.proxy(function (e) { this.update(selector, state, e.value); }, this)); // Make sure the event we just bound ourselves to is actually fired. new states.Trigger({ selector: selector, state: state }); + + // Update initial state value, if set by data attribute. + if ($dependee.data().hasOwnProperty('trigger:' + state.name)) { + this.values[selector][state.name] = $dependee.data('trigger:' + state.name); + } } } }, @@ -308,7 +316,7 @@ states.Trigger = function (args) { // Only call the trigger initializer when it wasn't yet attached to this // element. Otherwise we'd end up with duplicate events. - if (!this.element.data('trigger:' + this.state)) { + if (!this.element.data().hasOwnProperty('trigger:' + this.state)) { this.initialize(); } } @@ -319,7 +327,10 @@ states.Trigger.prototype = { var trigger = states.Trigger.states[this.state]; if (typeof trigger == 'function') { - // We have a custom trigger initialization function. + // Create data attribute for trigger, to prevent multiple + // calls to this method. + this.element.data('trigger:' + this.state, null); + // Call custom trigger initialization function. trigger.call(window, this.element); } else { @@ -329,14 +340,12 @@ states.Trigger.prototype = { } } } - - // Mark this trigger as initialized for this element. - this.element.data('trigger:' + this.state, true); }, defaultTrigger: function (event, valueFn) { var oldValue = valueFn.call(this.element); - + // Save current value to element data attribute. + this.element.data('trigger:' + this.state, oldValue); // Attach the event callback. this.element.bind(event, $.proxy(function (e) { var value = valueFn.call(this.element, e); @@ -344,13 +353,10 @@ states.Trigger.prototype = { if (oldValue !== value) { this.element.trigger({ type: 'state:' + this.state, value: value, oldValue: oldValue }); oldValue = value; + // Save current value to element data attribute. + this.element.data('trigger:' + this.state, value); } }, this)); - - states.postponed.push($.proxy(function () { - // Trigger the event once for initialization purposes. - this.element.trigger({ type: 'state:' + this.state, value: oldValue, oldValue: null }); - }, this)); } };