forked from knockout/knockout
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
var hasfocusUpdatingProperty = '__ko_hasfocusUpdating'; | ||
ko.bindingHandlers['hasfocus'] = { | ||
'init': function(element, valueAccessor, allBindingsAccessor) { | ||
var handleElementFocusChange = function(isFocused) { | ||
// Where possible, ignore which event was raised and determine focus state using activeElement, | ||
// as this avoids phantom focus/blur events raised when changing tabs in modern browsers. | ||
// However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers, | ||
// prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus | ||
// from calling 'blur()' on the element when it loses focus. | ||
// Discussion at https://github.com/SteveSanderson/knockout/pull/352 | ||
element[hasfocusUpdatingProperty] = true; | ||
var ownerDoc = element.ownerDocument; | ||
if ("activeElement" in ownerDoc) { | ||
isFocused = (ownerDoc.activeElement === element); | ||
} | ||
var modelValue = valueAccessor(); | ||
ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true); | ||
element[hasfocusUpdatingProperty] = false; | ||
}; | ||
var handleElementFocusIn = handleElementFocusChange.bind(null, true); | ||
var handleElementFocusOut = handleElementFocusChange.bind(null, false); | ||
|
||
ko.utils.registerEventHandler(element, "focus", handleElementFocusIn); | ||
ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE | ||
ko.utils.registerEventHandler(element, "blur", handleElementFocusOut); | ||
ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE | ||
}, | ||
'update': function(element, valueAccessor) { | ||
if (!element[hasfocusUpdatingProperty]) { | ||
var value = ko.utils.unwrapObservable(valueAccessor()); | ||
value ? element.focus() : element.blur(); | ||
ko.utils.triggerEvent(element, value ? "focusin" : "focusout"); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously | ||
} | ||
} | ||
}; |