【问题标题】:Knockout add method to already defined model淘汰赛将方法添加到已定义的模型
【发布时间】:2014-02-05 12:34:54
【问题描述】:

有什么方法可以向已经定义的模型添加新方法,例如

var MyModel = function() {

   var self = this;
   self.method1 = function () {
     return true;
   }
   self.method2 = function () {
     return true;
   }
};


viewModel = new MyModel ();
ko.applyBindings(viewModel);

这使我可以访问viewModel.method1()viewModel.method2(),但我希望稍后能够在文件中添加一个新方法,我可以以相同的方式访问该方法,例如

viewModel.extend = function() {
   self.method3 = function () {
     return true;
   }
}

现在我可以访问viewModel.method1()viewModel.method2()viewModel.method3()

有什么想法吗?

谢谢

【问题讨论】:

    标签: javascript mvvm knockout.js


    【解决方案1】:

    您可以使用原型定义一个:

    MyModel.prototype.method3 = function() {
        var self = this; // Reference to instance of MyModel
        var m1 = self.method1();
        var m2 = self.method2();
        return true;
    };
    

    在你的例子中:

    var MyModel = function() {
    
       var self = this;
       self.method1 = function () {
         return true;
       }
       self.method2 = function () {
         return true;
       }
    };
    
    
    viewModel = new MyModel ();
    ko.applyBindings(viewModel);
    
    MyModel.prototype.method3 = function() {
        return true;
    };
    
    console.log(viewModel.method3());
    

    【讨论】:

      猜你喜欢
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2014-04-08
      • 2013-12-24
      相关资源
      最近更新 更多