Search code examples
javascriptjquerytwitter-bootstrapdojoesri

In a jQuery click event, call a function stored in separate dojo js file


When trying to break up the JS code, I've pulled my jQuery bootstrap click events into their own file.

Everything loads correctly but when trying to reference a function that is in my dojo file from the jQuery file, the end result is "zoomToStreams not defined()";

Is there a proper way to break everything out into easily managed pieces for code-reusability and have the different libraries (jQuery, dojo) co-exist? Both are loaded via tags at the foot of my document.

// dojo.js

require(["dojo modules",...],function(dojo,...) {
    ...
    function zoomToStream(targetStream) {
       ...
    }
});

// jQuery.js

$(document).ready(function() {
    $("#streamSelection li").click(function(e) {
        switch (e.target.text) {
            case "All Streams":
                zoomToStream("all");
                break;
            case "First Stream";
                zoomToStream("1");
                break;
            ...
        }
    }
 });

Solution

  • Turn your first snippet into a module that you can then require for your jquery code.

    dojo.js (this isn't really what you named your js file is it?)

    define("zoomToStream",["dojo modules",...], function(dojo,...) {
        ...
        function zoomToStream(targetStream) {
           ...
        }
        return zoomToStream;
    });
    

    jQuery.js (this isn't really what you named your js file is it?)

    require(["zoomToStream"],function(zoomToStream) {
        $(document).ready(function() {
            $("#streamSelection li").click(function(e) {
                switch (e.target.text) {
                    case "All Streams":
                        zoomToStream("all");
                        break;
                    case "First Stream";
                        zoomToStream("1");
                        break;
                    ...
                }
            }
        });
    });
    

    modify to fit your file structure etc, kinda seems odd to use those filenames for your js files.