Archi Forum

Archi Plug-ins => jArchi => Topic started by: Gerald Groot Roessink on November 22, 2022, 20:31:06 PM

Title: Can jArchi object be a function return parameter
Post by: Gerald Groot Roessink on November 22, 2022, 20:31:06 PM
Good evening,
I created a function to find the element with a unique propertyvalue. Now I like to access the element from outside the function. Whatever I do. it comes up empty.
Is there a solution?
Thanks Gerald


// Function to find element with unique propertyvalue for propertykey
function find_element(propertyKey, propertyValue) {
    // Iterate through all elements in the model
    $("element").forEach(function(element) {
        // Find the property value at the given propertyKey
        var value = element.prop(propertyKey);
        if(value && value == propertyValue) {
console.log("   ", element);
return element;
}
    });
}"
Title: Re: Can jArchi object be a function return parameter
Post by: Phil Beauvoir on November 22, 2022, 21:22:44 PM
Hi,

you can't return from a forEach loop. Take a look here - https://medium.com/front-end-weekly/3-things-you-didnt-know-about-the-foreach-loop-in-js-ff02cec465b1

So you could do something like this:

function find_element(propertyKey, propertyValue) {
    var found;

    $("element").forEach(function(element) {
        var value = element.prop(propertyKey);
        if(value && value == propertyValue) {
            found = element;
        }
    });

    return found;
}
Title: Re: Can jArchi object be a function return parameter
Post by: Jean-Baptiste Sarrodie on November 22, 2022, 21:41:41 PM
Hi,

Another option is to use your function as a filter, and then iterate on the resulting collection:

var propertyKey = 'some name';
var propertyValue = 'some value';

result = $('element').filter(function(el) {return el.prop(propertyKey) == propertyValue}); // result is a collection

// Show all results
result.forEach(function(el) {console.log(el)});

Regards,

JB