Difference between knockout View Models declared as object literals vs functions

后端 未结 2 801
無奈伤痛
無奈伤痛 2020-11-22 14:44

In knockout js I see View Models declared as either:

var viewModel = {
    firstname: ko.observable(\"Bob\")
};

ko.applyBindings(viewModel );
2条回答
  •  萌比男神i
    2020-11-22 15:08

    I use a different method, though similar:

    var viewModel = (function () {
      var obj = {};
      obj.myVariable = ko.observable();
      obj.myComputed = ko.computed(function () { return "hello" + obj.myVariable() });
    
      ko.applyBindings(obj);
      return obj;
    })();
    

    Couple of reasons:

    1. Not using this, which can confusion when used within ko.computeds etc
    2. My viewModel is a singleton, I don't need to create multiple instances (i.e. new viewModel())

提交回复
热议问题