ro ko
ro ko

Reputation: 2986

dojo foreach function

I am quite new to dojo and I'm stuck with a problem here

I have a zend dojo form where I need to take sum of four elements and set the value to another element. I have assigned a class (score) to those four elements

".score" : {
     "found" : function (ele)  {
        var widgetId = ele.getAttribute('widgetid');                        
        dojo.connect(dijit.byId(widgetId),'onBlur', function(){

               var sum = 0;
               dojo.query('.score')
                    .forEach(function(ele){
                         var widgetId = ele.getAttribute('widgetid');
                         sum += parseInt(dijit.byId(widgetId).get('value'));
                });
           //***cannot get the value of sum here 
           dijit.byId('score_total').set('value', sum);
        });
    }
}

As commented I am unable to get the sum of those values outside the foreach. Is there any way to get the value out of the loop? Am I doing any thing wrong?

Upvotes: 0

Views: 3789

Answers (3)

addisu
addisu

Reputation: 634

One thing to note... dojo.foreach is deprecated ...

http://livedocs.dojotoolkit.org/dojo/forEach

instead ... array.forEach

http://livedocs.dojotoolkit.org/dojo/_base/array#forEach

but i think you might also have a scoping issue as well.. try something like this..

var sum = 0;
var elements = dojo.query('.score');

array.forEach(elements, function(ele) {
   var widgetId = ele.getAttribute('widgetid');
   sum += parseInt(dijit.byId(widgetId).get('value'));
});

Upvotes: 1

ro ko
ro ko

Reputation: 2986

It seems that I had made a mistake in the code and since I am quite new to jscript I was unable to debug. foreach indeed is not a asynchronous and sum was being calculated just that the parseInt(dijit.byId(widgetId).get('value')) was returning not a number NaN hence I was unable to populate the form element, I simply added an if condition and it worked

if(parseInt(dijit.byId(widgetId).get('value'))){
     sum = sum + parseInt(dijit.byId(widgetId).get('value'));
}

Sorry for the trouble

Upvotes: 2

Vijay Agrawal
Vijay Agrawal

Reputation: 3821

in your case, the parent context has the variable, so it will work as you have used it. Just a side point that if you want to access the sum variable outside the parent context, you will need to use dojo.hitch or pass the context to dojo.forEach

http://www.ibm.com/developerworks/web/library/wa-aj-dojo/

see the section on "Setting method context"

Upvotes: 0

Related Questions