RequireJS: How to define a constructor?

2019-05-14 00:04发布

I want to create constructors according to the AMD specification. I found this answer and tried to follow it. Here's what I ended up with:

main.js

requirejs.config({

    paths: {
        'jquery': 'vendor/jquery-1.9.1.min',
        'lodash': 'vendor/lodash-1.3.1.min',
        'knockout': 'vendor/knockout-2.2.1.min',
        'bootstrap': 'vendor/bootstrap-2.3.2.min'
    }
});

requirejs(
    ['jquery', 'lodash', 'knockout', 'controller/categories'], 
    function main($,_,ko, CategoriesCtrl) {

        var categories = new CategoriesCtrl();

    }
);

controller/categories.js

define('categories', function() {

    return function CategoriesCtrl(layers) {

        var self = this;
        layers = layers || [];

        console.log(ko);

    };
});

The result I get is that CategoriesCtrl is undefined. What have I done wrong?

1条回答
冷血范
2楼-- · 2019-05-14 00:26

You have created a named AMD module by making your first argument to define 'categories'. It's best to avoid this where possible:

You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name. It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names.

Try adjusting categories.js to this:

define(function() {

    return function CategoriesCtrl(layers) {

        // etc

    };
});
查看更多
登录 后发表回答