Creating a jQuery like “$” object

前端 未结 8 1344
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 03:25

My end goal is being able to do something like this:

MyVar(parameter).functionToPerform();

Silly enough, even after reading up on how varia

相关标签:
8条回答
  • 2020-12-08 04:18

    every time you call $ in jQuery it returns a new jQuery.init object. The jQuery.init object has functions that are then called.

    function test(type)
    {
      switch (type)
      {
        case 'azerty':
          return new type.a();
        case 'qwerty':
        default:
          return new type.b();
      }
    }
    
    test.a = function()
    {
      //a object defined
    };
    
    test.a.prototype.move = function()
    {
      //move function defined for the a object
    };
    
    etc...
    

    I just typed this on the fly, so it may need some tweaking

    This would allow you to call test('azerty').move();. More importantly: I hope you can see the general structure being used.

    Edit to add:

    To continue chaining functions like in jQuery, make sure you return the this object at the end of each function call:

    test.a.prototype.move = function()
    {
      //move function defined for the a object
      return this;
    };
    
    0 讨论(0)
  • 2020-12-08 04:19

    I've recently worked on an exercise that asked to re-create a JQuery like library using ES6 only.

    From the points above I was able to create the instantiation logic that makes it possible to call methods on selectors e.g class names.

    When the instance of $T is called with a selector a new instance of the $TLib is created on the particular selector which will contain all of the methods that can be used on the selector with the elements in context.

    I've added a couple of methods which are chainable in the example below which allows you to add a CSS class to an element and remove the same class in one call e.g:

    $T('.class-selector').addClass('green').removeClass('green);
    

    For those wanting to bootstrap something similar:

    const $T = (selector) => {
      // returns the HTML elements that match the selector
      const elements = document.querySelectorAll(selector);
      return new $TLib(elements, selector);
    };
    
    class $TLib {
      constructor (elements) {
        this._elements = elements;
      }
    
      addClass (className) {
        this._elements.forEach((element) => element.classList.add(className));
        return this;
      }
    
      removeClass (className) {
        this._elements.forEach((element) => element.classList.remove(className));
        return this;
      }
    
      toggleClass (className) {
        this._elements.forEach((element) => {
          const classList = element.classList;
          (classList.contains(className)) ? classList.remove(className) : classList.add(className);
        });
        return this;
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题