0

I'm working on a project written using Require.js. There are a number of reused functions that are currently being called from the global scope. These functions involve ui transitions, hide/show, and general on hover events. I want to organize these functions right into require, but not quite sure where/how to include them.

For example let's say in the app there are multiple spots that may call a common function of showDropdown(). And let's say it requires jQuery for the animation. Where or how would be the best place to store the showDropdown function?

Say a simple function like:

function showDropdown(id) {
    var thisdropdown = $(id).find('.dropdown');
    $(thisdropdown).slideDown();
}

I could create a UI folder, with the different js functions all being their own file. Then simply require them on any other files that are dependent on them. But regardless, those files will need to export their function to the global scope to be accessible correct?

I feel there is an obvious answer/setup as this must be fairly common item.

In addition, I am writing this in a backbone app, but I don't believe that has any direct impact, more of a require.js question.

1 Answer 1

3

Create a util library or something like that:

// util.js

define({
    showDropdown: function(id) {
        var thisdropdown = $(id).find('.dropdown');
        thisdropdown.slideDown();
    }    
});

Then use it elsewhere:

require(['util'], function(util) {

    util.showDropdown('my-id');

});
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, thanks. I knew it must be straight forward. Naturally in addition you would be able to define dependencies define(['jquery'],{ just like I'm needing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.