Javascript/Jquery Load Callback and Writing a Base Function

121 Views Asked by At

This might be a possible duplicate question but I do not know how to phrase the search for it. I'm not that familiar with JS properties.

CASE:

Lets say I create some element types such as Text,Image,Audio,Video etc. and suppose I give them the same abilities such as drag, rotate, resize etc. For simplicity, lets consider this two elements: Text and Image.

PROBLEM:

Lets say I need to get the sizes of those two elements and set those to their wrapper div.

  • Text element is simple, i can just get the size immediately and set the size of wrapper div.

  • Image element waits for the load of the image and its size can be set only after the load happens i.e. in its load callback.

SIMPLE EXAMPLE

function createText(){
    var aDiv = createWrapperDiv(); // <div class="element"></div>
    var anElem = $('<textarea></textarea>')
    aDiv.append(anElem)

    // can set immediately
    aDiv.attr('width', anElem.width());
    aDiv.attr('height', anElem.height());

    // Some other size-DEPENDENT and size-INDEPENDENT stuff can both be done here.
    sizeDependentStuff();
    sizeIndependentStuff();

}

function createImage(){
    var aDiv = createWrapperDiv(); // <div class="element"></div>
    var anElem = $('<img>')
    aDiv.append(anElem)

    // need to wait for element to load.
    anElem.attr('src',imageUrl)
    anElem.load(function(e) {
        aDiv.attr('width', e.currentTarget.width());
        aDiv.attr('height', e.currentTarget.height());

        // Some other size-DEPENDENT stuff.
        sizeDependentStuff();
    });

    // Some other size-INDEPENDENT stuff.
    sizeIndependentStuff();

}

WHAT I WANT:

I want to define a createSimpleElement function ( something similar to a Factory) that takes type and does both sizeDependentStuff and sizeIndependentStuff so I can reuse the same code. Note that i have more than 2 types and number can increase. I can not find a suitable way to tackle the load process.

I hope it is clear and please consider that I am still in the learning process.

Thanks.

1

There are 1 best solutions below

1
On BEST ANSWER

What about something like this?

function base(parentElement, element){
    parentElement.append(element);
    parentElement.attr('width', element.width());
    parentElement.attr('width', element.width());
    /*other common properties...*/
}

function createText(){
    var aDiv = createWrapperDiv();
    var anElem = $('<textarea></textarea>')
    base(aDiv, anElem);    
}

function createImage(){
    var aDiv = createWrapperDiv();
    var anElem = $('<img>')
    anElem.attr('src',imageUrl)
    anElem.load(function(e) {
        base(aDiv, anElem);   
    });

    // Some other size-INDEPENDENT stuff.

  }
}