Search code examples
knockout-3.0cropperjs

Can’t seem to access any parameters except allBindings in custom binding within event registered with registerEventHandler


I have a knockout custom binding that wraps functionality to an image crop library (https://github.com/fengyuanchen/cropper .) I’m catching the cropend.cropper event to (eventually) attach the cropped output to an observable.

I’m using:

  • knockout 3.3
  • jquery 2.1.4
  • cropper 2.0

Here is the binding handler:

    ko.bindingHandlers.cropper = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var $element = $(element);
            var value = ko.unwrap(valueAccessor());
            var a = 1;
            ko.utils.registerEventHandler(element, "cropend.cropper", function (event) {
                var previewOutputObservable = allBindings.get('previewOutput');
                var valueAccessorFromAllBindings = allBindings.get('cropper');
                var b = 1;
            });
            $element.cropper(value);
        },
        update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
            var $element = $(element);
            var value = ko.unwrap(valueAccessor());
            var c = 1;
        }
    };

And here is the element I'm binding to:

<img class="img-responsive" data-bind="attr: {'src': sampleObservable}, cropper: { aspectRatio: 16/9 }, previewOutput: cropPreview "/>

When I put a breakpoint (in chrome) on var b = 1; none of the parameters in the init are defined except allBindings. I’ve seen several examples use this general pattern though (e.g. here). What am I doing wrong?


Solution

  • The outer variables are accessible through a closure context. Chrome tries to optimize the context by only including variables that are actually accessed in the closure code. Since element wasn't accessed in your code, it's not part of the context. This is a good feature as it means that variables that aren't used in any closure can be safely disposed.