Add a line of code to ALL functions

后端 未结 3 1865
Happy的楠姐
Happy的楠姐 2020-11-30 15:53

So I am working in JS a lot, and I am working a lot with events (try to stay as modular as possible). Current I am calling Event.fire(\'eventName\') at the end

3条回答
  •  一整个雨季
    2020-11-30 16:30

    You could create a function that builds functions which always have that functionality:

    var eventFunctionFactory = function(fn, e) {
      if (typeof fn != 'function' || typeof e != 'function') {
        throw new TypeError('Invalid function!');
      }
    
      return function(/* arguments */) {
        // Convert arguments to array
        var args = Array.prototype.slice.call(arguments);
    
        // Fire event
        Event.fire(e);
    
        // Call the function with the applied arguments
        // Return its result
        return fn.apply(fn, args);
      };
    };
    
    var myClass = function() {
      this.someFunction = eventFunctionFactory(
                            // Function
                            function(a, b) {
                              return a + b;
                            },
    
                            // Event
                            function() {
                              console.log('someFunction fired!');
                            }
                          );
    };
    
    var myObj = new myClass();
    
    // Outputs:
    // someFunction fired!
    // 3
    console.log(myObj.someFunction(1, 2));
    

提交回复
热议问题