开发者

Using instance variables/methods within Reactive Framework subscription in Javascript

I've got an object in JS in which I'm trying to test out the Reactive Framework In an event subscription I'd like to call an instance method of the enclosing class where the subscription is defined, like this;

function MyClass()
{
    var DoSomething = function(a,b) { ... }

    var InstanceVariable = 1;

    this.uiEvent = uiDiv.jqueryUiWidget("widget")
        .toObservable("change")
        .Subscribe(
                function (event)
                {
                    // Want to call the instance method in the enclosing class
                    DoSomething(1,2);
                });

    this.uiEvent2 = uiDiv.jqueryUiWidget("widget")
        .toObservable("change")
        .Subscribe(
                function (event)
                {
                    // Want to use the instance variable within here
                    alert(InstanceVari开发者_运维技巧able);  
                });
}

How can I do this (since the "this" scope is that of the subscription)? Do I have to pass the function/variable through when setting up the subscription in some way?

If I attempt to do this, I get an error in all browsers saying that the instance variables or methods don't exist: "this" within the scope of the function where I want to call the instance members refers to the Observer and so has functions of OnNext, OnCompleted etc.

Many Thanks,

Paul


Seems to me like your code should work. If you are having any problems I suggest you describe them. However, if you are asking how it works, then you should know about closures. From Wikipedia:

In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be "closed over" its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself. The explicit use of closures is associated with functional programming and with languages such as ML and Lisp. Closures are used to implement continuation passing style, and in this manner, hide state. Constructs such as objects and control structures can thus be implemented with closures.

This means that DoSomething and InstanceVariable are accessible from any method that is defined within the scope where they are defined. There will be a new "instance" of these variables each time the MyClass constructor is called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜