Lost reference to self when using KnockoutJS and Simple Class Inheritance

后端 未结 2 1178
误落风尘
误落风尘 2021-01-28 09:07

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 t

2条回答
  •  误落风尘
    2021-01-28 09:39

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

    Edit:

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

提交回复
热议问题