使用 KnockoutJS 和简单类继承时丢失对 self 的引用 [英] Lost reference to self when using KnockoutJS and Simple Class Inheritance

查看:16
本文介绍了使用 KnockoutJS 和简单类继承时丢失对 self 的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 John Resig 的简单 JavaScript 继承" 创建一个类可以继承.我也将 KnockoutJS 用于计算的 observables.问题在于试图将这两个概念结合起来.当我尝试在计算的 observable 中获得对 self 的引用时,我得到了Window"对象而不是预期的实际对象.这是一个快速代码示例:

I am using John Resig's "Simple JavaScript Inheritance" to create a class that can be inherited. I am also using KnockoutJS for computed observables. The problem comes in trying to combine these two concepts. When I try to gain a reference to self in the computed observable I get the "Window" object instead of the expected actual object. Here is a quick code sample:

window.mynamespace.myclass = Class.extend({
    init: function() {

    },
    someProperty: ko.observable(10),
    someComputedProperty: ko.computed(function() {
       return this.someProperty();  
    }, this)
});

不幸的是,无法找到 this.someProperty(),因为this"是对 Window 的引用.有什么想法或想法吗?

Unforunately this.someProperty() is unable to be found because 'this' is a reference to Window. Any thoughts or ideas?

推荐答案

您始终可以在 init 中添加它们.在 knockout 自己的示例中,他们在构造函数中进行绑定.

You could always add them in the init. In knockout's own examples they do their binding in the constructor.

window.mynamespace.myclass = Class.extend({
    init: function() {
        this.someProperty = ko.observable(10);
        this.someComputedProperty = ko.computed(function() {
           return this.someProperty();  
        }, this);  
    }
});

或者捕获对this的引用而忘记绑定:

Or capturing a reference to this and forgetting about binding:

window.mynamespace.myclass = Class.extend({
    init: function() {
        var self = this;
        self.someProperty = ko.observable(10);
        self.someComputedProperty = ko.computed(function() {
           return self.someProperty();  
        });  
    }
});

<小时>

演示如何扩展类:


To demonstrate how you'd extend the class:

window.mynamespace.myotherclass = window.mynamespace.myclass.extend({
    init: function() {
      // do anything myotherclass init, like another observable
      this.someOtherProperty = ko.observable(10);

      // incidentally you *can* have private variables with this pattern
      var imPrivate = 1;
      this.getImPrivate = function() {
        return imPrivate;
      };

      // then call super (maybe with arguments, maybe just passing them)
      this._super('foobar');
    }
});

这篇关于使用 KnockoutJS 和简单类继承时丢失对 self 的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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