简体   繁体   中英

MEAN stack using jade, where to put page specific JS?

I have an app running on the MEAN stack. I am using jade for templates and was wondering where to put page specific javascript. Right now my directory looks like:

app/
 |- public
 |   |- js
 |   |- css
 |- views
 |- routes
 |- schemas

One of my views, signup.jade , I need to include some javascript:

$(function() {

    $.validator.addMethod("passwordStrength", function( value, element ) {
        console.log("here")
        var result = this.optional(element) ||
                        /^[a-zA-Z0-9- ]*$/.test(value) &&
                        /\d/.test(value) &&
                        /[a-z]/i.test(value);
        if (!result) {
            var validator = this;
        }
        return result;
    }, "Your password must contain at least one number and one special character.");

    $('#signup').validate({
        rules: {
            email: {
                required: true
            },

            password: {
                required: true,
                passwordStrength: true,
                minlength: 6
            },

            "repeat-password": {
                required: true,
                passwordStrength: true,
                minlength: 6
            }
        }
    });
});

Where is the best place to put this? Do I create a javascript file for each page inside of app/public/js?

If anyone has any good articles on MEAN file structure best practices as a whole those would be appreciated as well, thanks!

From my experience it is completely fine to keep script in the corresponding jade view if such script is used only once.

You can however create directory with helpers and move this script to this directory (just create a plain js file) and then add it on the page by adding a variable and set its value to the file content. It may look a little bit more clean (and allows you to apply js lint to helpers, etc) but requires a bit more work.

在此处输入图片说明 Here is how my code is organized. We are using angular fullstack generator by yeoman. In the image i provided, home.html is the partial view whose controller is home.js. I suggest you create a separate file for every html partial page you create. As a matter of fact, a good angular page should have user defined directives, and respective Controllers hooking scope into the directives and the directives managing the scope that has been provided. It keeps it neat/simple/beautiful. If you get a chance and can afford it, buy the ng-book. It is beautiful, else even angular's guide is amazing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM