使用KnockoutJS和Simple Class Inheritance时失去对self的引用 [英] Lost reference to self when using KnockoutJS and Simple Class Inheritance
问题描述
我使用 John Resig的简单JavaScript继承来创建一个类可以继承。我也在使用KnockoutJS来计算可观察量。问题在于尝试将这两个概念结合起来。当我尝试在计算的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
。在敲除自己的示例中,他们在构造函数中进行绑定。
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);
}
});
或者捕获对的引用
并忘记关于绑定:
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和Simple Class Inheritance时失去对self的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!