sg.cc
sg.cc

Reputation: 1816

Save jQuery selector and function to variable

I have a Save/Edit button. I would like it to do different things depending on whether it's currently a Save button or an Edit button. For clarity, I want to save the jQuery selector and function to a variable name, then call it:

    $('div#' + id + ' .edit').click(function(){

        var i = this;
        var state = function(st){
            if( typeof st !== 'undefined')
                $(i).html(st);
            else
                return $(i).html();
        };

        if( state() == 'Edit' ) {
            controller.edit(id);
            state('Save');
        } else {
            controller.save();
            state('Edit');
        }

    });

My question: is there a faster way to do this? Something like the following:

    $('div#' + id + ' .edit').click(function(){

        var state = $(this).html;

        if( state() == 'Edit' ) {
            controller.edit(id);
            state('Save');
        } else {
            controller.save();
            state('Edit');
        }

    });

...but this does not work.

This example is just an example; I know there are many ways to do what it's trying to do without saving the selector and the function to a variable. Nonetheless, the question still stands: is it possible to do this faster?

Upvotes: 0

Views: 177

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

jQuery elements are objects so why not store directly into your Object element the desired state:

DEMO

$('div#' + id + ' .edit').click(function(){
  var es = this.es ^= 1;           // Toggle/Store state
  $(this).text(es?'Save':'Edit');
  return controller[es?'edit':'save'](id);
});

Upvotes: 0

adeneo
adeneo

Reputation: 318212

Why not just

$('#' + id + ' .edit').on('click', function(){
    $(this).text(function(_, txt) {
        if (txt == 'Edit') {
            controller.edit(id);
            return 'Save';
        } else if (txt == 'Save') {
            controller.save();
            return 'Edit';
        }
    });
});

Upvotes: 3

Related Questions