How to access outer function observable in inner f

2019-09-02 17:38发布

问题:

I am having a main function and sub function inside that, like this:

var main= function () {
    var self = this;
    self.value1 = ko.observable("");
     var data =   self.value1();   
     self.revaluate = ko.computed(function(){ 
     data = self.self.value1(); // i am overwriting 
     });

    function inner(i1,i2)
    {
        var self= this ;

        self.id1=ko.observable(i1);
        self.id2=ko.observable(i2);
        self.value2 = ko.observable("");

        self.visibility = ko.computed(function() {
            if (data == 1) {return true;}
            else {false;}
        });
    }
}

ko.applyBindings(new main());

I need the value1 value inside my inner function that should be dynamic.

I tried storing it in a variable and accessing it, but it's not gonna solve my case as there is a scenario where self.visibility won't fire at all and update dynamically.

Onload I get an updated value1 so everything will work, but I have a button "goto next stage", and onclick of that button I am updating the status, i.e self.value1(2). At this point self.visibility should update as there is change in value1.

I tried to show what I need in a simple example, but in reality there's some more complex looping going on.

Any clue will be great.

回答1:

For your computed to update when self.value1 updates you actually have to use it inside computed function

self.visibility = ko.computed(function(){
        if( self.value1() == 1)
            {return true;}
        else
           { return false;}
         });
        }

Main reason why your computed didn't work is because you were using data to calculate the computed which is a simple JS variable, that is why it updated only onload, data never actually reevaluated, so your computed never got updated. What you need to use is an ko.observable for computed to update properly!

One other note: I don't see that you've used any variable from inner function in your computed. If that is the case in your real example than you can simply transfer the computed to main function.

Edit: As I don't have a working code, and don't know how are you using this inner function I can't create a working example just point to problems. self.value1 will have scope problems but you should be able to overcome this, try passing it as a variable, use global variable... Whichever works for you



标签: knockout.js