从外部ViewModel调用Knockout函数

时间:2014-03-18 21:30:45

标签: javascript knockout.js

在我的具体示例中,有几个不同的小部件具有自己的封装ViewModel。我需要一个全局的Save按钮来保存每个ViewModel。我似乎无法弄清楚如何在各个ViewModel上调用函数。

示例 - 如何在每个ViewModel上调用Save函数:http://jsfiddle.net/sNSh2/4/

var ViewModel1 = function() {
    var self = this;
    self.firstName = ko.observable('');
    self.lastName = ko.observable('');

    self.firstName('John');
    self.lastName('Doe');

    self.Save = function () {
        alert(ko.toJSON(self));
    };
};
ko.applyBindings(new ViewModel1(), document.getElementById("person"));

var ViewModel2 = function() {
    var self = this;
    self.subscriptionLevel = ko.observable('');

    self.subscriptionLevel('premier');

    self.Save = function () {
        alert(ko.toJSON(self));
    };
};
ko.applyBindings(new ViewModel2(), document.getElementById("subscription"));

$('#save').on('click', function() {

});

3 个答案:

答案 0 :(得分:14)

我不明白你的问题,为什么不简单地拿一个模型对象的参考?

$(function() {
  ...
  var m1 = new ViewModel1();
  ko.applyBindings(m1, document.getElementById("person"));

  ...
  var m2 = new ViewModel2();
  ko.applyBindings(m2, document.getElementById("subscription"));

  $('#save').on('click', function() {
    m1.Save();
    m2.Save();
  });
});

如果你真的有问题要获取所有模型对象的引用(可能在隔离的js文件中定义),ko提供了从关联的DOM对象中获取上下文对象的方法。你仍然可以这样做:

ko.contextFor(document.getElementById("person")).$data.Save();
ko.contextFor(document.getElementById("subscription")).$data.Save();

答案 1 :(得分:1)

Knockout具有基本的发布/订阅功能。尝试使用尺寸jsFiddle

var postbox = ko.observable();

var ViewModel1 = function() {
    var self = this;
    self.firstName = ko.observable('');
    self.lastName = ko.observable('');

    self.firstName('John');
    self.lastName('Doe');

    self.Save = function () {
        alert(ko.toJSON(self));
    };
    postbox.subscribe(function(newValue){
        self.Save();
    }, self, 'save');
};
ko.applyBindings(new ViewModel1(), document.getElementById("person"));

var ViewModel2 = function() {
    var self = this;
    self.subscriptionLevel = ko.observable('');

    self.subscriptionLevel('premier');

    self.Save = function () {
        alert(ko.toJSON(self));
    };

    postbox.subscribe(function(newValue){
        self.Save();
    }, self, 'save');
};
ko.applyBindings(new ViewModel2(), document.getElementById("subscription"));

$('#save').on('click', function() {
    postbox.notifySubscribers(null, "save");
});

答案 2 :(得分:0)

您只需要实例化ViewModel1和ViewModel2函数:

$('#save').on('click', function() {
   var vm1 = new ViewModel1(),
       vm2 = new ViewModel2();

   vm1.SayHi();
   vm2.SayHi();
});