如何将javascript模块加载到另一个模块中以供使用,例如我想让一个moudule有一个对象,我想用它来创建另一个模块中的该对象的实例。
示例:对象模块:
`
define(["knockout"],function(){
var postobj = function(name,age){
this.name = ko.observable(name);
this.age = ko.observable(age);
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
&#13;
define(["knockout"],function(ko){
this.posts = ko.observableArray();
var people = [{name: "katuula Kalali Joel", age: "23"},
{name: "keman Migadde", age: "30"},
{name: "Ntanda Hakim", age: "19"}];
jQuery.each(people,function(index,value){
this.posts.push(new imageobj(value['name'],value['age']));
},this);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
&#13;
我收到此错误&#34;未捕获的ReferenceError:postobj未定义&#34;
答案 0 :(得分:2)
您可能希望将原始模块作为对第二个模块的引用。在第二个中,看起来您正在使用imageobj
,但我假设它与您的postobj
类似。
所以,你希望你的模块看起来像:
define(["knockout"],function(){
var postobj = function(name,age){
this.name = ko.observable(name);
this.age = ko.observable(age);
};
// important to return the value of your module
return postobj;
});
在第二个模块中,您将拉入第一个模块,如:
define(["knockout", "path/to/postobj"],function(ko, Postobj){
function ViewModel() {
this.posts = ko.observableArray();
var people = [{name: "katuula Kalali Joel", age: "23"},
{name: "keman Migadde", age: "30"},
{name: "Ntanda Hakim", age: "19"}];
jQuery.each(people,function(index,value){
this.posts.push(new Postobj(value['name'],value['age']));
},this);
}
return new ViewModel();
});