Benefit of declaring knockout view model using IIF

2019-08-10 02:46发布

While I learn to use knockout js, I have read from various source on declaring view model as object literal and function. Generally, it came to me that the conclusion is declaring view model as function is a better choice (correct me if i am wrong).

Recently, it came to me that some member in stackoverflow use this method to declare view model instead. Though i do not know what this method call as it is not being introduced in any book or elsewhere. Hope someone can clarify what benefit of using this compare to object literal and function.

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

  ko.applyBindings(obj);
  return obj;
})();

2条回答
闹够了就滚
2楼-- · 2019-08-10 02:58

This is not declaring the view model as a function. It is declaring an anonymous function inline and then executing it, returning an object. It is the same as declaring an object inline, except the object is returned from the function. In other words, this is just a style, and really not important.

However, for a different style (actually declaring the view model as a function) see Difference between knockout View Models declared as object literals vs functions

It's just a matter of style, really.

查看更多
成全新的幸福
3楼-- · 2019-08-10 03:10

It's a matter of choosing the right tool for the job. Some viewmodels may be very simple, and so can be defined as inline objects. I often find that it helps to have the ability to define helper functions and private variables, in which case I will use the immediately-executing function form that you are asking about.

It is pretty rare that I need to create multiple instances of a viewmodel. If I did, I would use a named function that returns a viewmodel object.

As rare as it is to make multiple viewmodels of the same form, it is rarer still to need to inherit from them, or to need so many instances that sharing methods via prototype is a significant help. These are the only circumstances that warrant using actual constructors.

查看更多
登录 后发表回答