diff --git a/misc/states.js b/misc/states.js index f82ab42..2c1eecc 100644 --- a/misc/states.js +++ b/misc/states.js @@ -109,16 +109,19 @@ states.Dependent.prototype = { // Monitor state changes of the specified state for this dependee. $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 }); + if ($dependee.length) { + $dependee.bind('state:' + state, $.proxy(function (e) { + this.update(selector, state, e.value); + }, this)); - // 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); + // 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); + } } } } @@ -313,12 +316,7 @@ states.Trigger = function (args) { if (this.state in states.Trigger.states) { this.element = $(this.selector); - - // 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().hasOwnProperty('trigger:' + this.state)) { - this.initialize(); - } + this.initialize(); } }; @@ -346,8 +344,9 @@ states.Trigger.prototype = { 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) { + // Detach possibly earlier attached event callback using event namespacing + // and attach a new event callback. + this.element.unbind(event + '.statesDefaultTrigger').bind(event + '.statesDefaultTrigger', $.proxy(function (e) { var value = valueFn.call(this.element, e); // Only trigger the event if the value has actually changed. if (oldValue !== value) {