I am attempting to use Knockout.js and the jQuery autosize plugin for a comment stream system. Basically, when a comment input is focused, I use the Knockout.js event binding shown below:
data-bind="event: {focus: $parent.autosize, blur: $parent.resize}"
In my model, I implement the autosize
function as follows:
$self.autosize = function(data, event) {
var textarea = $(event.target);
textarea.autosize();
});
From what I can tell, however, event
is undefined
, and I am unable to use it to find the textarea so that I can call autosize()
on it. I am also unable to query the textarea's attributes, and when I use console.log
to find the value of event
I am given undefined
back.
This only appears to be happening in Internet Explorer. Particularly version 8-9. IE 10 as well as Chrome, Firefox, etc. work as expected. Is there a known issue with Knockout.js event binding and Internet Explorer in this manner?
In IE you would need to access event.srcElement
rather than event.target
. So, you could do var textArea = $(event.target || event.srcElement);
A more "Knockout" like solution though would be to add a quick custom binding that would keep that logic out of your view model like:
ko.bindingHandlers.autosize = {
init: function(element) {
ko.utils.registerEventHandler(element, "focus", function() {
$(element).autosize();
});
ko.utils.registerEventHandler(element, "resize", function() {
//whatever you call here
});
}
};
Then, just put data-bind="autosize: true"
on your element.