jQuery addClass example

Change class name on click in jQuery

by JeyDotC

HTML

<form id="some-form">
  <fieldset>
    <legend>To Do</legend>
    <p id="help"></p>
    <textarea id="todo-text"></textarea>
    <button id="add-button">Add</button>
  </fieldset>
  <ul id="todos">
  
  </ul>
</form>

JavaScript

function TodoViewModel() {
  this.help = tie.text('#help', 'This is a one-direction binding.');
  this.text = tie.value('#todo-text');
  
  this.add = tie.click('#add-button', function() {
    this.help = this.text;
  });
}

function tieBinding(type, selector, initialValue) {
  this.type = type;
  this.selector = selector;
  this.value = initialValue;

  this.apply = function($context, viewModel, propertyName) {
    Object.defineProperty(viewModel, propertyName, this.type($context, this.selector, this.value));
  };
}

function tieMethod(type, selector, initialValue) {
  this.type = type;
  this.selector = selector;
  this.value = initialValue;

  this.apply = function($context, viewModel, propertyName) {
    viewModel[propertyName] = this.type($context, this.selector, viewModel, this.value);
  };
}

const tie = {
  types: {
    text: function($context, selector, initialValue) {
      let $el = $context.find(selector).text(initialValue);
      return {
        get: function() {
          return $el.text();
        },
        set: function(value) {
          $el.text(value);
        }
      };
    },
    value: function($context, selector, initialValue) {
      let $el = $context.find(selector).val(initialValue);
      return {
        get: function() {
          return $el.val();
        },
        set: function(value) {
          $el.val(value);
        }
      };
    },
    click: function($context, selector, viewModel, method) {
      $context.find(selector).on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        method.call(viewModel, e);
      });
      return method;
    }
  },
  text: function(selector, value) {
    return new tieBinding(tie.types.text, selector, value);
  },
  value: function(selector, value) {
    return new tieBinding(tie.types.value, selector, value);
  },
  click: function(selector, method) {
    return new tieMethod(tie.types.click, selector, method);
  },
  apply: function(selector, viewModel) {
   ...