Search code examples
javascriptdurandalsyncfusion

Durandal widgets inner function scope and context


I have durandal widget and two syncfusion buttons:

view.html

<div class="group-btn-container">            
    <input type="checkbox" data-bind="ejToggleButton: toggleButtonNo" />
    <input type="checkbox" data-bind="ejToggleButton: toggleButtonYes" />
</div>

viewmodel.js

define(['knockout', 'jquery','web/ej.togglebutton.min', 'common/ej.widget.ko.min'], function (ko, $) {

    var ctor = function () { };

    ctor.prototype.activate = function (settings) {
        self = this;

        var toggleBtnYes = {         
            toggleState: ko.observable(false),
            click: function (args) {
                self.toggleButtonNo.buttonOptions.toggleState(false);
                args.model.toggleState(true);
            }
        }
        self.toggleButtonYes = toggleBtnYes;

        var toggleBtnNo = {          
            toggleState: ko.observable(true),
            click: function (args) {
                self.toggleButtonYes.buttonOptions.toggleState(false);
                args.model.toggleState(true);
            }
        }
        self.toggleButtonNo = toggleBtnNo;
    };
    return ctor;
});

Two buttons 'Yes' and 'No', should work like radio buttons, when one is turned on, another should be turned off.

Q1: I have a problem with viewodel context or scope. Inside click function I do not see 'self', actually self is always some another widget because in one loop I render couple widgets, I do not know why self is not my function ctor ?

Q2: Also when I want to approach to object 'toggleBtnNo' or 'toggleBtnYes' directly from click function, they are not defined. Why I cannot see the objects from global function ctor in my inner, 'click' function?

I just do not know how to approach to the button (on one or other way) from my click function how I can change it state ?


Solution

  • This was the worst mistake ever. I was looking at that million times and did not notice. I am ashamed.

    I did not put 'var' in front of self.

    self = this;  
    

    should be:

    var self = this;
    

    It caused that self goes to the global scope and every time some other widget overwrites value of self.