使用IIFE声明基因剔除视图模型的好处 [英] Benefit of declaring knockout view model using IIFE

查看:66
本文介绍了使用IIFE声明基因剔除视图模型的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我学习使用淘汰赛js时,我从各种来源阅读了有关将视图模型声明为对象文字和函数的信息.通常,我得出的结论是将视图模型声明为函数是一个更好的选择(如果我错了,请纠正我).

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).

最近,我发现stackoverflow中的某些成员使用此方法来声明视图模型.尽管我不知道此方法调用的内容,因为在任何书中或其他地方都没有介绍它.希望有人可以阐明将其与对象文字和函数进行比较的好处.

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;
})();

推荐答案

要为工作选择合适的工具.一些视图模型可能非常简单,因此可以定义为内联对象.我经常发现,定义辅助函数和私有变量的功能会有所帮助,在这种情况下,我将使用您所要求的立即执行的函数形式.

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.

我很少需要创建一个视图模型的多个实例.如果这样做,我将使用一个命名函数,该函数返回一个viewmodel对象.

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.

这篇关于使用IIFE声明基因剔除视图模型的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆