Shelby115
Shelby115

Reputation: 2865

function handle jQuery event and parameter?

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.)

Upvotes: 1

Views: 119

Answers (1)

Felix Kling
Felix Kling

Reputation: 817208

Use .call to set this correctly:

updateEntity.call(this, e);

Learn more about this.

Upvotes: 2

Related Questions