Skip to content

Instantly share code, notes, and snippets.

@fpotter
Created November 4, 2010 00:06
Show Gist options
  • Save fpotter/661924 to your computer and use it in GitHub Desktop.
Save fpotter/661924 to your computer and use it in GitHub Desktop.
/**
* What follows is an awful, awful solution for catching native paste events
* on CPTextField and properly firing the textDidChange event.
*
* It doesn't yet handle cut.
*
* I only did it this way because I was in a big rush for a demo, and didn't
* want to fork Cappuccino at the time.
*/
@import <Foundation/Foundation.j>
function Swizzle(cls, originalSelector, newSelector)
{
var originalMethod = class_getInstanceMethod(cls, originalSelector);
var newMethod = class_getInstanceMethod(cls, newSelector);
method_exchangeImplementations(originalMethod, newMethod);
}
@implementation CPTextField (Additions)
- (void)PItextDidFocus:(CPNotification)note
{
[self _inputElement].onpaste = function(e, elName)
{
var originalString = [self stringValue];
[self deleteBackward:self];
var selectedRange = [self selectedRange],
stringValue = [self stringValue],
pasteString = e.clipboardData.getData("Text"),
newValue = [stringValue stringByReplacingCharactersInRange:selectedRange withString:pasteString];
[self setStringValue:newValue];
[self setSelectedRange:CPMakeRange(selectedRange.location+pasteString.length, 0)];
var modifiedString = [self stringValue];
if (originalString !== modifiedString)
{
[self textDidChange:[CPNotification notificationWithName:CPControlTextDidChangeNotification object:self userInfo:nil]];
}
// If we don't do this, we get hit twice for some reason.
e.preventDefault();
};
// Call original impl
[self PItextDidFocus:note];
}
- (void)PItextDidBlur:(CPNotification)note
{
[self _inputElement].onpaste = null;
// Call original impl
[self PItextDidBlur:note];
}
@end
function PatchCPTextField()
{
Swizzle([CPTextField class], @selector(textDidFocus:), @selector(PItextDidFocus:));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment