Search code examples
jqueryknockout.jsautosize

Autosize knockout custom binding autosize on load


I have a custom knockout binding for jquery autosize that I want to have autosize on page load.

Here is a fiddle of the issue

Example of code:

 ko.bindingHandlers.autogrow = {

 init: function (element, valueAccessor, allBindingsAccessor) {

     ko.utils.registerEventHandler(element, 'focusout', function () {
         var observable = valueAccessor();
         observable($(element).val());
     });

     ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
         $(element).data('autosize').remove();
     });

     $(element).autosize({ append: "\n" });

     $(element).focus(function () {
         $(element).trigger('autosize');
     });
 },

 update: function (element, valueAccessor) {
     var value = ko.utils.unwrapObservable(valueAccessor());
     $(element).val(value);
     $(element).trigger("autosize");
   }
};

var vm = {};
vm.Data = ko.observable("This is a lot of text and has to display correctly");

ko.applyBindings(vm);

Example of html:

<textarea id="autogrow" class="text-nm span2" data-bind="autogrow: Data"></textarea>

What happens is I have a lot of text that I want to display in a text area but the amount differs every time, so I have no set amount that will display that I know before hand. What I want to do is after the knockout bindings have been applied I want to trigger the autosize event of the autosize plug in, but I can't figure out when and where.

Thanks


Solution

  • I've might misunderstood the question, but this works in FF atleast

    http://jsfiddle.net/3p9bj/13/

    I removed the update function and let autosize do its thing under the hood

    I also use the value binding for updating value

    ko.applyBindingsToNode(element, { value: valueAccessor() });