1

Take the following code,

// Update button clicked
function updateEntity(e) {
    e.preventDefault();

    var name = $(this).attr("name");

    ...
    // some stuff
    ...
}

$(document).on("click", ".updateEntity", updateEntity);

Currently I have this for (go figure) updating an entity I've editted on button click. Now, its parameter is particularly expecting a jQuery event. However, I want to also be able to call this function (end goal: to minimize code) outside of a jQuery event. Like so,

// Do an update but then redirect to prevent adding the same estimate twice.
function createEstimate(e) {
    updateEntity(e);

    var link = $(this).attr("href");
    window.location.href = link;
}

$(document).on("click", ".createEntity", createEstimate);

Question: How would I go about calling updateEntity or setting the function up, so that I can supply it to the click-event handler and call it like a function and still have it used correctly? Is this goal realistic or should I be structuring this differently if I want to achieve such a goal?

(Encase it is not obvious, my current problem is that on the function call updateEntity(e); $(this) becomes window instead of the clicked link.)

1 Answer 1

2

Use .call to set this correctly:

updateEntity.call(this, e);

Learn more about this.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, wasn't expecting the question to have that simple of an answer. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.