简体   繁体   English

内部函数作用域的访问元素,而不是敲除中的外部元素

[英]accessing element of inner function scope instead of outer in knockout

I have my code below. 我下面有我的代码。 I have var viewData in my constructor appVM as null and in activate I am filling it with some value. 我在构造函数appVM中将var viewData设置为null,并在激活中使用一些值填充它。 Now I have to use activate scope of viewData instead of outer scope. 现在,我必须使用viewData的激活范围而不是外部范围。 what my self var of Lis should be assign with for the same. 我的Lis自我变数应该分配给什么。

var appVM = function () {        
    this.viewData = null;
    this.subscription = ko.observable();      

    this.activate = function (viewActivationData) {
        var self = this;
        self.viewData = viewActivationData.viewData;
    };

appVM.prototype.list = function () {
    var self = this;
    getEmpLists(self.viewData.empId);
};

You'll want to do a search for tutorials about how closures work in JavaScript. 您将需要搜索有关闭包如何在JavaScript中工作的教程。

Here are a couple of ways to solve your issue: 以下是解决问题的几种方法:

First: (Creates a closure for 'this') 第一:(为“ this”创建一个闭合)

var appVM = function () {        
    var self = this;
    this.viewData = null;
    this.subscription = ko.observable();      

    this.activate = function (viewActivationData) {
        self.viewData = viewActivationData.viewData;
    };

    appVM.prototype.list = function () {
        getEmpLists(self.viewData.empId);
    };
}

Second: (Avoids the need for a closure) 第二:(避免关闭)

var appVM = function() {
  var viewData = null;
  var subscription = ko.observable();

  var activate = function(viewActivationData) {
    viewData = viewActivationData.viewData;
  };

  var list = function() {
    getEmpLists(viewData.empId);
  };

  return {
    viewData: viewData,
    subscription: subscription,
    activate: activate,
    list: list,
  };
}

These are just two simple example. 这只是两个简单的例子。 There are other ways you could solve this, but these are probably the most simple. 您可以通过其他方法解决此问题,但这可能是最简单的方法。 Ultimately you'll need to use several different techniques when controlling and understanding 'this'. 最终,在控制和理解“ this”时,您需要使用几种不同的技术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM