我有一个模块require.js:
define([], function() {
return {
test:function (value,element,params )
{
if (value.length == 0 && params.mandatory === "True")
return false;
return true;
}
}
});
我需要在这个模块中添加第二个函数“test2”,我该怎么做?
答案 0 :(得分:2)
很简单,你要返回一个对象文字,所以要为它添加另一个属性:
define([], function() {
return {
test:function (value,element,params )
{
if (value.length == 0 && params.mandatory === "True")
{
return false;
}
return true;
},//<-- comma to separate properties, much like {foo:'bar', val: 1234}
test2: function()
{//here's test2 definition
}
};
});
也就是说,传递给define的回调允许你花时间:
define([], function()
{
var mod = {};
mod.test = function(value, element, params)
{
return !(value.length == 0 && params.mandatory === "True");//does the same as your code
};
mod.test2 = function()
{
var value = 'foobar', params = {mandatory: true};//instead of checking True, pass bool if possible?
return mod.test(value, null, params);//instead of this: much safer!
};
return mod;//return object here
}