简体   繁体   English

通过define中的require调用传递requirejs中的参数

[英]Passing parameters in requirejs via a require call in define

I am new to requirejs and AMD module functions, and I am trying to pass a parameter from a require call, but I am running into some troubles. 我是requirejs和AMD模块功能的新手,我试图通过require调用传递参数,但遇到了一些麻烦。 I am trying to pass the obj in a require call to the fun method. 我试图将obj传递给fun方法的require调用。 This require call is within a define method as shown in the code below. 该require调用在定义方法内,如下面的代码所示。 I following the instructions from this blog: http://blog.novanet.no/4-strategies-for-passing-parameters-to-requirejs-modules/ 我按照此博客中的说明进行操作: http : //blog.novanet.no/4-strategies-for-passing-parameters-to-requirejs-modules/

define(['require'],function(require){
    var obj= {name:'random'};
    require({
        config : {
           'tagging' : obj
        }
    },['fun'],function(promise){
        promise.then(function(ret){
        //do something.
      });
   }   
}

Then I want to use the passed obj parameter in this below code. 然后,我想在下面的代码中使用传递的obj参数。 In fun.js 在fun.js中

//Passing obj to fun.js //将obj传递给fun.js

define(['module','lie'],function(data,Promise){
    var promise = new Promise(function(res,rej){
        //do something
    });
}

But instead I am getting the following error on the console: 但是相反,我在控制台上收到以下错误:

TypeError: depMaps.slice is not a function TypeError:depMaps.slice不是函数

Any clues on fixing this? 有关解决此问题的任何线索?

PS:Also if there are any better methods, kindly let me know. PS:如果还有更好的方法,请告诉我。

Thanks, 谢谢,

This can be done easily by returning a function which returns the promise rather than returning the promise directly. 通过返回一个返回诺言的函数而不是直接返回诺言,可以很容易地做到这一点。 Then you can pass the data to this function for getting the promise and do whatever calculations that you want to do with the promise and data. 然后,您可以将数据传递给此函数以获取承诺,并执行您希望对承诺和数据进行的任何计算。

define(['require'],function(require){
    var obj= {name:'random'};
    var data = {
       'tagging' : obj
    }
    require(['fun'],function(promiseGetter){
      promiseGetter(data).then(function(ret){
        //do something.
      });
   }   
}

and fun.js 和fun.js

define(['lie'],function(Promise){
    var promise = new Promise(function(res,rej){
        //do something
    });
    return function(data){ 
         //DO whatever you want to do with data here
         return promise;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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