简体   繁体   中英

how to load modules into other modules in knockout js AMD helpers

how can i load javascript modules into another module for use for example i want to have one moudule having an object which i want to use to create instances of that object in another module.

example: object module:

`

 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> 
and for the second part of the module i have this code

 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); }); 
 <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> 

i get this error "Uncaught ReferenceError: postobj is not defined "

You would want to pull your original module in as a reference to the second module. In the second one, it looks like you are using imageobj , but I am assuming that it would be a similar scenario to your postobj .

So, you would want your modules to look something like:

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;
});

In the second module, you would pull in your first module like:

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();

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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