Giter Site home page Giter Site logo

Consider factory functions about pickr HOT 6 CLOSED

simonwep avatar simonwep commented on May 22, 2024
Consider factory functions

from pickr.

Comments (6)

SaulDoesCode avatar SaulDoesCode commented on May 22, 2024 2

class vs factory function: general structure comparison

this is just for interest's sake.
note: this is my take on the matter and could be very wrong indeed, tread carefully.

classes

class X {
   constructor (props) {
      Object.assign(this, {...X.defaults}, props)
   }
   
   method () {
     // do something
     console.log(`state: a: ${this.a}, b: ${this.b}, c: ${this.c}`)
   }

   //  ... more methods ...
}
// static defaults
X.defaults = {a: 1, b: 2, c: 3}

// USE:
const myX = new X({a: 45, b: 32});
myX.method()
// > state: a: 45, b: 32, c: 3

factory function

const X = (props = {}) => {
      // create object (equivalent to a class's 'this')
      const x = {
          ...X.defaults,
          ...props,

          method () {
              // do something
             console.log(`state: a: ${x.a}, b: ${x.b}, c: ${x.c}`)
          }

         //  ... more methods ...
      }
    
     // constructor area
    // ...nothing to do here...

   // return object as if it would be a class instance
   return x
}

// static defaults
X.defaults = {a: 1, b: 2, c: 3}

// USE:
const myX = X({a: 45, b: 32});
myX.method()
// > state: a: 45, b: 32, c: 3

now super condensed

const X = (props = {}) => (props = {
   ...X.defaults,
   ...props,
   method () { 
     console.log (`state: a: ${props.a} b: ${props.b} c: ${props.c}`)
   }
})
X.defaults = {a: 1, b: 2, c: 3}
moveable.js as a factory function
import * as _ from './../lib/utils';

export default function Moveable(opt) {
    const M = {
        // Assign default values
        options: Object.assign({
            lockX: false,
            lockY: false,
            onchange: () => 0
        }, opt),

        _tapstart(evt) {
            _.on(document, ['mouseup', 'touchend', 'touchcancel'], M._tapstop);
            _.on(document, ['mousemove', 'touchmove'], M._tapmove);

            // Trigger move
            M.trigger(evt);

            // Prevent default touch event
            evt.preventDefault();
        },

        _tapmove(evt) {
            const element = M.options.element;
            const b = M.wrapperRect;

            let x, y;
            if (evt) {
                const touch = evt && evt.touches && evt.touches[0];
                x = evt ? (touch || evt).clientX : 0;
                y = evt ? (touch || evt).clientY : 0;

                // Reset to bounds
                if (x < b.left) x = b.left;
                else if (x > b.left + b.width) x = b.left + b.width;
                if (y < b.top) y = b.top;
                else if (y > b.top + b.height) y = b.top + b.height;

                // Normalize
                x -= b.left;
                y -= b.top;
            } else if (M.cache) {
                x = M.cache.x;
                y = M.cache.y;
            } else {
                x = 0;
                y = 0;
            }

            if (!M.options.lockX)
                element.style.left = (x - element.offsetWidth / 2) + 'px';

            if (!M.options.lockY)
                element.style.top = (y - element.offsetHeight / 2) + 'px';

            M.cache = {x, y};
            M.options.onchange(x, y);
        },

        _tapstop() {
            _.off(document, ['mouseup', 'touchend', 'touchcancel'], M._tapstop);
            _.off(document, ['mousemove', 'touchmove'], M._tapmove);
        },

        trigger(evt) {
            M.wrapperRect = M.options.wrapper.getBoundingClientRect();
            M._tapmove(evt);
        },

        update(x = 0, y = 0) {
            M._tapmove(new MouseEvent('mousemove', {
                clientX: M.wrapperRect.left + x,
                clientY: M.wrapperRect.top + y
            }));
        },

        destroy() {
            _.off([M.options.wrapper, M.options.element], 'mousedown', M._tapstart);
            _.off([M.options.wrapper, M.options.element], 'touchstart', M._tapstart, {
                passive: false
            });
        }
    }

    M.wrapperRect = M.options.wrapper.getBoundingClientRect();

    _.on([M.options.wrapper, M.options.element], 'mousedown', M._tapstart);
    _.on([M.options.wrapper, M.options.element], 'touchstart', M._tapstart, {
        passive: false
    });

    return M;
}

from pickr.

simonwep avatar simonwep commented on May 22, 2024 2

Okay, (finally) I've borrowed it :)
It has proven itself to be very useful, was able to go down from 23,7 KB (24.303 bytes) to 22,6 KB (23.242 bytes). With some other changes even to 22,6 KB (23.177 bytes) 🎉 Altogether an awesome idea :D

from pickr.

simonwep avatar simonwep commented on May 22, 2024 1

Yeah, that's true... would simplify a lot. I personally prefer ES6 classes 'cause I use babel anyway and it will be transpiled to ES5 constructor functions. And they are more legible IMO. But you're basically right, I will take this in consideration / try it out.

from pickr.

simonwep avatar simonwep commented on May 22, 2024 1

Hahaha, thank's 😄, I will have!
Also thank's for being so active, your improvements / suggestions are awesome! Helps a lot to improve this library!

from pickr.

SaulDoesCode avatar SaulDoesCode commented on May 22, 2024

I agree factories are not as clean looking as classes, that's fair 😐.
Thanks for giving it a try though 👍.
But either way happy coding! 😃

from pickr.

simonwep avatar simonwep commented on May 22, 2024

Reminds me of the Java-Factory-Pattern :D. Basically a very clean style, and can be better minified!

from pickr.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.