Home > Enterprise >  if not trigger inside object array
if not trigger inside object array

Time:11-26

Object array does not execute the "if" when call a method with the forEach but when I move the if inside of the forEach it works, I am trying to figure out why is not trigger the if inside the object when run the forEach.

There is a var (responseFlag) with the default value (false) so if you need to change the html render just change it (true/false) when the button is clicked.

        var responseFlag = 'false',
        targetRender = document.getElementById('targethtml'),
        templateTrue = '<h2>true</h2>',
        templateFalse = '<h2>false</h2>';
        
        // 
        objDef = {
            "objDefs" : [
                {
                    "UIhtml": responseFlag == 'true' ? templateTrue : templateFalse // does not works
                    // "UIhtml": responseFlag // this works
                }
            ]
        };

        // 
        UI_exc = {
            outputResult: function() {
                objDef.objDefs.forEach(function(key, value){
                    targetRender.innerHTML = 
                    // responseFlag == 'true' ? templateTrue : templateFalse // this works
                    key.UIhtml // does not works
                    console.log(responseFlag)
                });
    
            },
            clickAction: function() {
                document.getElementById('goRender').addEventListener("click", function(){
                    responseFlag = 'true' // render html base true/false
                    console.log(responseFlag);
                    UI_exc.outputResult()
                });
            }
        };

        UI_exc.clickAction();
<button id="goRender">Click</button>
<div id="targethtml">[ N ]</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The problem I guess is that object is initialized and the UIhtml property is assigned there, I think you should change UIhtml to a function and then call it:

... = key.UIhtml()
console.log(responseFlag) 

CodePudding user response:

When creating object literals, the declared properties is not a string, rather it is a just a reference to some value e.g strings, numbers, booleans, objects...

Change the "UIhtml" to UIhtml.

Read this documentation for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

  • Related