Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dropzone.js within a knockout binding

I am trying to get dropzone to work as a knockout binding. I would really like to be able to...

ko.bindingHandlers.dropzone = {
    init: function(element, valueAccessor, allBindingsAccessor, bindingContext) {
        $(element).dropzone({ url: 'some/tightly/bound/uri});
    }
}

.. but I cannot. The uri is dynamic based on data entered in the viewmodel, so this is what I have come up with so far:

var dropzoneObject; // probably should be this.dropzoneObject

ko.bindingHandlers.dropzone = {
    init: function(element, valueAccessor, allBindingsAccessor, bindingContext) {
        var url = allBindingsAccessor().urlPath || "unknown";
        dropzoneObject = new Dropzone("div#" + element.id, {
            url: url, 
            init: ...,
            etc
        });
    },
    update: function(element, valueAccessor, allBindingsAccessor, bindingContext) {
        var url = allBindingsAccessor().urlPath || "unknown";
        dropzoneObject.options = {
            url: url
        };
    }
}

but when I test this, I get the following error:

Uncaught TypeError: Cannot read property 'trim' of undefinedDropzone.defaultOptions.addedfile 
@ dropzone.js:252Emitter.emit @ dropzone.js:58Dropzone.addFile 
@ dropzone.js:956(anonymous function) @ dropzone.js:563

Why is it undefinedDropzone? What have I missed?

Thanks

like image 453
Matt Avatar asked Jul 07 '15 14:07

Matt


People also ask

What is binding in knockout JS?

A binding consists of two items, the binding name and value, separated by a colon. Here is an example of a single, simple binding: Today's message is: <span data-bind= "text: myMessage" ></span> An element can include multiple bindings (related or unrelated), with each binding separated by a comma.

How do I use knockout js in HTML?

It is very easy to use KnockoutJS. Simply refer the JavaScript file using <script> tag in HTML pages. A page as in the following image will be displayed. Click on download link and you will get the latest knockout.


1 Answers

Found the answer, my update method was over writing all the options (including the default ones) rather than updating it so:

....
update: function(element, valueAccessor, allBindingsAccessor, bindingContext) {
    var url = allBindingsAccessor().urlPath || "unknown";
    dropzoneObject.options = {
        url: url
    };
}
....

Should read:

update: function(element, valueAccessor, allBindingsAccessor, bindingContext) {
    var url = allBindingsAccessor().urlPath || "unknown";
    dropzoneObject.options.url = url;
}

Hope this helps someone!

like image 81
Matt Avatar answered Sep 16 '22 20:09

Matt