Knockout function call from outside ViewModel

In my specific example, there are several different widgets that have their own encapsulated ViewModel. I need a global Save button that saves each individual ViewModel. I cannot figure out how to call functions on individual ViewModels.

Example. How can I call the Save function on each ViewModel: 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() {

});
+4
source share
3 answers

I do not understand your problem, why not just keep the reference to the model object?

$(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();
+11

pub/sub. 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");
});
+1

You just need to instantiate the functions ViewModel1 and ViewModel2:

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

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

Source: https://habr.com/ru/post/1532374/


All Articles