【问题标题】:how to load modules into other modules in knockout js AMD helpers如何在淘汰赛js AMD助手中将模块加载到其他模块中
【发布时间】:2015-04-29 22:15:22
【问题描述】:

如何将 javascript 模块加载到另一个模块中以供使用,例如,我希望一个模块具有一个对象,我想使用该对象在另一个模块中创建该对象的实例。

示例:对象模块:

`

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>
对于模块的第二部分,我有这个代码

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>

我收到此错误“未捕获的 ReferenceError:未定义 postobj”

【问题讨论】:

    标签: jquery twitter-bootstrap knockout.js requirejs knockout-amd-helpers


    【解决方案1】:

    您可能希望将原始模块作为对第二个模块的引用。在第二个中,看起来您正在使用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();
    
    });
    

    【讨论】:

    • 非常感谢 ryan,你在 48 小时的忙碌之后的救命稻草
    猜你喜欢
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多