Search code examples
javascriptjointjs

Getting max text length out of all rows


How to get the length of all the text from all rows. I have problem with variable scoping. I am getting only the text length of last row.

Code:

pointerclick: function (evt, x, y) {
    var className = evt.target.parentNode.getAttribute('class');

    if (className === 'element-tool-remove')
    {
        this.model.remove();
        console.log("element removed");

        var embeddedCells = parent1.getEmbeddedCells();

        var t = new Array();      
        var maxTextLength;
        for(var d = 0; d < embeddedCells.length; d++)
        {
            t[d] = embeddedCells[d].attributes.attrs.text.text.length;
            var maxTextLength = Math.max(t[d]);
            //console.log("max text length is: " + maxTextLength);
        }
        console.log("max text length is: " + maxTextLength); // printing only last element's text length but not the max value out of all
    }
    joint.dia.CellView.prototype.pointerclick.apply(this, arguments);
}

How do I get the max value out of all the rows?


Solution

  • Try:

    pointerclick: function (evt, x, y) {
        var className = evt.target.parentNode.getAttribute('class');
    
        if (className === 'element-tool-remove')
        {
            this.model.remove();
            console.log("element removed");
    
            var embeddedCells = parent1.getEmbeddedCells();
    
            var t = new Array();      
            var maxTextLength = 0;
            for(var d = 0; d < embeddedCells.length; d++)
            {
                t[d] = embeddedCells[d].attributes.attrs.text.text.length;
                maxTextLength = Math.max(t[d], maxTextLength);
                //console.log("max text length is: " + maxTextLength);
            }
            console.log("max text length is: " + maxTextLength); // printing only last element's text length but not the max value out of all
        }
        joint.dia.CellView.prototype.pointerclick.apply(this, arguments);
    }
    

    I've assigned 0 as a default to the maxTextLength variable and in the loop I'm replacing the value of maxTextLength if the new value is larger. I do not have a way to test that code, but it should work.