3
\$\begingroup\$

In order to avoid boilerplate code and make an extensible pool of actions for the same portion of code (a row of texts to edit), I've prepared this code.

var actions = {
    editName: function () {
        var curName = this.nameField.text();

        this.nameField.data('oldName', curName);
        this.nameField.html('<input class="updatedName" type="text" value="' + curName + '"/>');
        this.actionsField.append('<a href="#" class="action" data-action="cancelEdit">Cancel</a>');
        this.remove();
    },
    cancelEdit: function () {
        var oldName = this.nameField.data('oldName');

        this.nameField.html(oldName);
        this.actionsField.append('<a href="#" class="action" data-action="editName">Edit</a>');
        this.remove();
    }
};

$('.field').on('click', '.actions a[data-action]', function (ev) {
    ev.preventDefault();

    var link = $(this);
    var action = link.data('action');

    if (typeof actions[action] === 'function') {
        var fieldSelector = link.closest('.field');

        this.nameField = fieldSelector.find('.name');
        this.actionsField = fieldSelector.find('.actions');

        actions[action].call(this);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field">
    Name: <div class="name">WiL</div>
    <div class="actions">
        <a href="#" data-action="editName">Edit</a>
    </div>
</div>

The main goal is to define, only once, the selectors and use them in the functions. To accomplish this, the selectors are defined out of the function calls and later adding functions like save, copy, erase or whatever your imagination allows.

I have a few concerns, too:

  1. In the early versions of the code, I used var for the nameField selector, but no functions in the actions object were able to see it (and therefore use it). Why does it work with this?

  2. Performance implications of using this to define a variable (instead of var).

  3. In this line:

    var action = link.data('action');
    

    I use link "naked", without a jQuery wrapper because I know that already is a jQuery object, but should I wrap it in $() again? Are there any performance issues of "double wrapping"?

\$\endgroup\$

0

Your Answer

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

Browse other questions tagged or ask your own question.