RequireJS: How to define a constructor?

大兔子大兔子 提交于 2019-12-22 10:48:20

问题


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:


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

    };
});


来源:https://stackoverflow.com/questions/17368491/requirejs-how-to-define-a-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!