javascript design pattern - callback though a public method - javascript

I'd like to be able to use a public method for a callback instead of passing it as an argument
as in
function Car() {
var that = this;
this.onGearChanged = function(callback) {
callback();
};
setTimeout(that.onGearChanged, 2000);
}
var car = new Car();
car.onGearChanged(function(){
console.log("gear changed");
});
instead of
var onGearChanged = function(){
console.log("gear changed")
}
var car = new Car(arg, arg, onGearChange);
how would I go about it? Should i follow an observer pattern?

I think you need something like this:
function Event(sender) {
this._sender = sender;
this._listeners = [];
}
Event.prototype = {
attach: function (listener) {
this._listeners.push(listener);
},
notify: function (args) {
for (var i = 0; i < this._listeners.length; i++) {
this._listeners[i](this._sender, args);
}
}
};
You Car class:
function Car(gear) {
var self = this;
self.Gear = gear;
self.GearChanged = new Event(this);
//Example method to trigger your GearChanged event. In your real code, you may have different logic
self.changeGear = function (newGear){
self.Gear = newGear;
//notify all subscribers
self.GearChanged.notify(newGear);
}
}
Example code to subscribe to events:
var car = new Car("gear");
car.GearChanged.attach(function (sender,args){
console.log("gear changed");
console.log("new gear value is:" + args);
});
//do some logic that may trigger gearChanged event.
car.changeGear("new Gear");
You can attach more event handlers and all these event handlers will get called. And you can also add more events like: tireChanged,.. easily with this structure.

The code will be more or less complex, depending on your requirements that are not clear. Don't use a pattern if you don't need it, and a pattern can be adjusted in many ways depending on your requirements. Don't try to build the all-for-all solution if you don't realy need it.
If you have many observers and know them at creation time of the car, you can use
function Car(onGearChangedArray) {
this.triggerGearChanged = function() {
for (var i=0;i<onGearChangedArray.length;i++) {
onGearChangedArray[i]();
}
};
window.setTimeout(this.triggerGearChanged,2000);
}
var car = new Car([function(){
console.log("gear changed");
}]);
If you only have exactly one observer, you can get rid of the for loop.
But if you need the flexibility to add them at runtime:
function Car() {
var onGearChangedCallbacks = [];
this.onGearChanged = function(callback) {
onGearChangedCallbacks.push(callback);
};
this.triggerGearChanged = function() {
for (var i=0;i<onGearChangedCallbacks.length;i++) {
onGearChangedCallbacks[i]();
}
};
window.setTimeout(this.triggerGearChanged,2000);
}
var car = new Car();
car.onGearChanged(function(){
console.log("gear changed");
});
Or if you want to abstract it the next level
function Event() {
var callbacks = [];
this.bind = function(callback) {
callbacks.push(callback);
};
this.fire = function() {
for (var i=0;i<callbacks.length;i++) {
callbacks[i]();
}
};
}
function Car() {
this.gearChanged = new Event();
window.setTimeout(this.gearChanged.fire,2000);
}
var car = new Car();
car.gearChanged.bind(function(){
console.log("gear changed");
});
Thanks for the abstraction idea to Khanh TO, I just wanted to show it without parameters.
You could also consider using something more sophisticated, so that you don't need to write this event handling code yourself (like error handling etc.), but again, it depends on your needs. Do you need a fail fast strategy, or should errors be just logged? Must Listeners be unregistered? Could you trap yourself in an infinite loop because triggerGearChanged could lead to another triggerGearChanged? Do you need to pass parameters or not? Keep in mind to keep it as simple as possible, so if you don't need to pass parameters, then don't do it.
If you like unserscore.js, a good start may be http://mattmueller.me/blog/underscore-extension-observer-pattern

Related

Spy function with elementary JavaScript syntax [duplicate]

The main reason why I want it is that I want to extend my initialize function.
Something like this:
// main.js
window.onload = init();
function init(){
doSomething();
}
// extend.js
function extends init(){
doSomethingHereToo();
}
So I want to extend a function like I extend a class in PHP.
And I would like to extend it from other files too, so for example I have the original init function in main.js and the extended function in extended.js.
With a wider view of what you're actually trying to do and the context in which you're doing it, I'm sure we could give you a better answer than the literal answer to your question.
But here's a literal answer:
If you're assigning these functions to some property somewhere, you can wrap the original function and put your replacement on the property instead:
// Original code in main.js
var theProperty = init;
function init(){
doSomething();
}
// Extending it by replacing and wrapping, in extended.js
theProperty = (function(old) {
function extendsInit() {
old();
doSomething();
}
return extendsInit;
})(theProperty);
If your functions aren't already on an object, you'd probably want to put them there to facilitate the above. For instance:
// In main.js
var MyLibrary = {
init: function init() {
}
};
// In extended.js
(function() {
var oldInit = MyLibrary.init;
MyLibrary.init = extendedInit;
function extendedInit() {
oldInit.call(MyLibrary); // Use #call in case `init` uses `this`
doSomething();
}
})();
But there are better ways to do that. Like for instance, providing a means of registering init functions.
// In main.js
var MyLibrary = (function() {
var initFunctions = [];
return {
init: function init() {
var fns = initFunctions;
initFunctions = undefined;
for (var index = 0; index < fns.length; ++index) {
try { fns[index](); } catch (e) { }
}
},
addInitFunction: function addInitFunction(fn) {
if (initFunctions) {
// Init hasn't run yet, remember it
initFunctions.push(fn);
} else {
// `init` has already run, call it almost immediately
// but *asynchronously* (so the caller never sees the
// call synchronously)
setTimeout(fn, 0);
}
}
};
})();
Here in 2020 (or really any time after ~2016), that can be written a bit more compactly:
// In main.js
const MyLibrary = (() => {
let initFunctions = [];
return {
init() {
const fns = initFunctions;
initFunctions = undefined;
for (const fn of fns) {
try { fn(); } catch (e) { }
}
},
addInitFunction(fn) {
if (initFunctions) {
// Init hasn't run yet, remember it
initFunctions.push(fn);
} else {
// `init` has already run, call it almost immediately
// but *asynchronously* (so the caller never sees the
// call synchronously)
setTimeout(fn, 0);
// Or: `Promise.resolve().then(() => fn());`
// (Not `.then(fn)` just to avoid passing it an argument)
}
}
};
})();
There are several ways to go about this, it depends what your purpose is, if you just want to execute the function as well and in the same context, you can use .apply():
function init(){
doSomething();
}
function myFunc(){
init.apply(this, arguments);
doSomethingHereToo();
}
If you want to replace it with a newer init, it'd look like this:
function init(){
doSomething();
}
//anytime later
var old_init = init;
init = function() {
old_init.apply(this, arguments);
doSomethingHereToo();
};
The other methods are great but they don't preserve any prototype functions attached to init. To get around that you can do the following (inspired by the post from Nick Craver).
(function () {
var old_prototype = init.prototype;
var old_init = init;
init = function () {
old_init.apply(this, arguments);
// Do something extra
};
init.prototype = old_prototype;
}) ();
Another option could be:
var initial = function() {
console.log( 'initial function!' );
}
var iWantToExecuteThisOneToo = function () {
console.log( 'the other function that i wanted to execute!' );
}
function extendFunction( oldOne, newOne ) {
return (function() {
oldOne();
newOne();
})();
}
var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );
2017+ solution
The idea of function extensions comes from functional paradigm, which is natively supported since ES6:
function init(){
doSomething();
}
// extend.js
init = (f => u => { f(u)
doSomethingHereToo();
})(init);
init();
As per #TJCrowder's concern about stack dump, the browsers handle the situation much better today. If you save this code into test.html and run it, you get
test.html:3 Uncaught ReferenceError: doSomething is not defined
at init (test.html:3)
at test.html:8
at test.html:12
Line 12: the init call, Line 8: the init extension, Line 3: the undefined doSomething() call.
Note: Much respect to veteran T.J. Crowder, who kindly answered my question many years ago, when I was a newbie. After the years, I still remember the respectfull attitude and I try to follow the good example.
This is very simple and straight forward. Look at the code. Try to grasp the basic concept behind javascript extension.
First let us extend javascript function.
function Base(props) {
const _props = props
this.getProps = () => _props
// We can make method private by not binding it to this object.
// Hence it is not exposed when we return this.
const privateMethod = () => "do internal stuff"
return this
}
You can extend this function by creating child function in following way
function Child(props) {
const parent = Base(props)
this.getMessage = () => `Message is ${parent.getProps()}`;
// You can remove the line below to extend as in private inheritance,
// not exposing parent function properties and method.
this.prototype = parent
return this
}
Now you can use Child function as follows,
let childObject = Child("Secret Message")
console.log(childObject.getMessage()) // logs "Message is Secret Message"
console.log(childObject.getProps()) // logs "Secret Message"
We can also create Javascript Function by extending Javascript classes, like this.
class BaseClass {
constructor(props) {
this.props = props
// You can remove the line below to make getProps method private.
// As it will not be binded to this, but let it be
this.getProps = this.getProps.bind(this)
}
getProps() {
return this.props
}
}
Let us extend this class with Child function like this,
function Child(props) {
let parent = new BaseClass(props)
const getMessage = () => `Message is ${parent.getProps()}`;
return { ...parent, getMessage} // I have used spread operator.
}
Again you can use Child function as follows to get similar result,
let childObject = Child("Secret Message")
console.log(childObject.getMessage()) // logs "Message is Secret Message"
console.log(childObject.getProps()) // logs "Secret Message"
Javascript is very easy language. We can do almost anything. Happy JavaScripting... Hope I was able to give you an idea to use in your case.
Use extendFunction.js
init = extendFunction(init, function(args) {
doSomethingHereToo();
});
But in your specific case, it's easier to extend the global onload function:
extendFunction('onload', function(args) {
doSomethingHereToo();
});
I actually really like your question, it's making me think about different use cases.
For javascript events, you really want to add and remove handlers - but for extendFunction, how could you later remove functionality? I could easily add a .revert method to extended functions, so init = init.revert() would return the original function. Obviously this could lead to some pretty bad code, but perhaps it lets you get something done without touching a foreign part of the codebase.

How function reference works in js?

Recently I've been trying to use pixi.js for some fun project and I come across a concept that I do not understand at all. Quoting some code:
PIXI.loader
.add([
"images/one.png",
"images/two.png",
"images/three.png"
])
.on("progress", loadProgressHandler)
.load(setup);
function loadProgressHandler(loader, resource) {
console.log(`loading: ${resource.url}`);
};
How these arguments (loader, resource) are passed to the function since we only pass the reference to it in the event listener? Can someone show a generic implementation beneath that concept?
Lets say we have a function called callMe that just prints a number that its given:
function callMe(number) {
console.log(`I'm number: ${number}`);
}
callMe(2);
We can create a new variable to that same function, and call the newly created variable. This is possible since it's pointing to the same function that we've created earlier.
const callMeAswell = callMe;
callMe(3);
callMeAswell(4);
In short, this is what's happing inside the PIXI loaders, except for that it's stored somewhere else for you. Lets create a class to store the numbers and the function that we want to call:
function SomeLoader(){
this.numbers = []; // list of numbers we want to store for later usage
this.func = null; // function that we want to call when we're done loading
}
SomeLoader.prototype.add = function(number) {
this.numbers.push(number); // add the number to the list of numbers
}
SomeLoader.prototype.on = function(func) {
this.func = func; // just store the function for now, but don't do anything with it
}
SomeLoader.prototype.pretendToLoad = function() {
for(const number of this.numbers) {
this.func(number); // now we're going to call the function that we've stored (callMe in the example below)
}
}
const loader = new SomeLoader();
loader.add(5);
loader.add(6);
loader.on(callMe);
loader.pretendToLoad();
Or fluently:
function SomeLoader(){
this.numbers = [];
this.func = null;
}
SomeLoader.prototype.add = function(number) {
this.numbers.push(number);
return this;
}
SomeLoader.prototype.on = function(func) {
this.func = func;
return this;
}
SomeLoader.prototype.pretendToLoad = function() {
for(const number of this.numbers) {
this.func(number);
}
}
new SomeLoader()
.add(7)
.add(8)
.on(callMe)
.pretendToLoad();
Looks almost the same as the PIXI loaders, doesn't it? :)
Arguments are passed to the function when it is called.
The code which calls that function isn't in the question. It is done somewhere behind the on function.
In short: The same way as normal, you just aren't looking at the point where it happens.
const show = value => console.log(value);
const call_callback_with_hello_world = callback => callback("Hello, world");
call_callback_with_hello_world(show);
What #Quentin said is correct - adding on to that however...
A generic concept beneath that implemention is called a callback and would look like so:
function Loop(callback, index){
callback(index);
}
function CallbackFunction(val){
console.log(val)
}
for(var i = 0; i < 5; i++){
Loop(CallbackFunction, i);
}

How to invoke a function from both an outside and a sibling function in javascript / google app script

Basic question but I can't figure it out :(. A solution to one makes the other one break. Here is the specific case narrowed down, any help is appreciated.
function onOpen() { // first entry point
var helper = new level1Function();
helper.level2FunctionA();
}
function onFormSubmit() { // second entry point
var helper = new level1Function();
helper.level2FunctionC();
}
function level1Function() {
this.level2FunctionA = function() {
console.log('hi');
}
function level2FunctionB() {
// how do I invoke level2FunctionA from here w/o breaking onOpen entry point?
}
this.level2FunctionC = function() {
level2FunctionB();
}
}
onOpen();
onFormSubmit();
// looking for 2 hi's to the console, one through each flow
create a reference to a variable self, assign to this at the top of the function body
function level1Function() {
var self = this;
this.level2FunctionA = function() {
console.log('hi');
}
function level2FunctionB() {
self.level2FunctionA();
}
this.level2FunctionC = function() {
level2FunctionB();
}
}
Another solution, instead of creating a reference to self as that is error-prone in many situations, you could use Function.prototype.bind and create a function boundLevel2FunctionB, which has this bound to the current level1Function instance (I see you're calling it using the new keyword).
Code:
[...] // level2Function body
function level2FunctionB() {
this.level2FunctionA();
}
var boundLevel2FunctionB = level2FunctionB.bind(this);
this.level2FunctionC = function() {
boundLevel2FunctionB();
}
[...]
Cheers!

jQuery mobile touch event handling, this keyword context, and properly using closures

Forgive me if I'm not very clear here. I'm trying to learn a lot of things at once by doing.
I have an event listener with multiple events like this:
$account.on({
tap: function() {
accountOpen = true;
ui.openAccount(this);
},
swiperight: etc. etc.
}
I have all my ui functions in an object literal. Example:
var ui = PROJECT.ui = {
openAccount: function(account) {
var $account = $(account),
$trans = $('.transactions'),
$closeBtn= $account.find('.close-btn');
$account.removeClass('pay-open').removeClass('move-open');
$trans.appendTo($a)
.slideDown(400,function(){
$closeBtn.fadeIn(100);
});
}
}
What's the proper way to send the event target / this from the event handler to ui.openAccount() function without have to repeatedly capture the vars? (i.e. how do I stop repeating myself?) Do I use a constructor? Is there where an account object with a closure would come in handy?
I was thinking something like this:
var account = (function(){
var acct = {
this.container = $(this),
this.closeBtn = $(this).find('.close-btn')
}
return acct;
}());
And I could send the var account to ui.openAccount(), but I know i'm definitely not doing it right.
Try passing the event to the function you are calling:
$account.on({
tap: function(e) {
var my_cool_new_object = {};
console.log("your event is here")
console.log(e)
accountOpen = true;
// populate your object
my_cool_new_object.target = e.target;
my_cool_new_object.foo = bar;
...
// pass to method
ui.openAccount(my_cool_new_object);
},
swiperight: etc. etc.
}

Javascript: Extend a Function

The main reason why I want it is that I want to extend my initialize function.
Something like this:
// main.js
window.onload = init();
function init(){
doSomething();
}
// extend.js
function extends init(){
doSomethingHereToo();
}
So I want to extend a function like I extend a class in PHP.
And I would like to extend it from other files too, so for example I have the original init function in main.js and the extended function in extended.js.
With a wider view of what you're actually trying to do and the context in which you're doing it, I'm sure we could give you a better answer than the literal answer to your question.
But here's a literal answer:
If you're assigning these functions to some property somewhere, you can wrap the original function and put your replacement on the property instead:
// Original code in main.js
var theProperty = init;
function init(){
doSomething();
}
// Extending it by replacing and wrapping, in extended.js
theProperty = (function(old) {
function extendsInit() {
old();
doSomething();
}
return extendsInit;
})(theProperty);
If your functions aren't already on an object, you'd probably want to put them there to facilitate the above. For instance:
// In main.js
var MyLibrary = {
init: function init() {
}
};
// In extended.js
(function() {
var oldInit = MyLibrary.init;
MyLibrary.init = extendedInit;
function extendedInit() {
oldInit.call(MyLibrary); // Use #call in case `init` uses `this`
doSomething();
}
})();
But there are better ways to do that. Like for instance, providing a means of registering init functions.
// In main.js
var MyLibrary = (function() {
var initFunctions = [];
return {
init: function init() {
var fns = initFunctions;
initFunctions = undefined;
for (var index = 0; index < fns.length; ++index) {
try { fns[index](); } catch (e) { }
}
},
addInitFunction: function addInitFunction(fn) {
if (initFunctions) {
// Init hasn't run yet, remember it
initFunctions.push(fn);
} else {
// `init` has already run, call it almost immediately
// but *asynchronously* (so the caller never sees the
// call synchronously)
setTimeout(fn, 0);
}
}
};
})();
Here in 2020 (or really any time after ~2016), that can be written a bit more compactly:
// In main.js
const MyLibrary = (() => {
let initFunctions = [];
return {
init() {
const fns = initFunctions;
initFunctions = undefined;
for (const fn of fns) {
try { fn(); } catch (e) { }
}
},
addInitFunction(fn) {
if (initFunctions) {
// Init hasn't run yet, remember it
initFunctions.push(fn);
} else {
// `init` has already run, call it almost immediately
// but *asynchronously* (so the caller never sees the
// call synchronously)
setTimeout(fn, 0);
// Or: `Promise.resolve().then(() => fn());`
// (Not `.then(fn)` just to avoid passing it an argument)
}
}
};
})();
There are several ways to go about this, it depends what your purpose is, if you just want to execute the function as well and in the same context, you can use .apply():
function init(){
doSomething();
}
function myFunc(){
init.apply(this, arguments);
doSomethingHereToo();
}
If you want to replace it with a newer init, it'd look like this:
function init(){
doSomething();
}
//anytime later
var old_init = init;
init = function() {
old_init.apply(this, arguments);
doSomethingHereToo();
};
The other methods are great but they don't preserve any prototype functions attached to init. To get around that you can do the following (inspired by the post from Nick Craver).
(function () {
var old_prototype = init.prototype;
var old_init = init;
init = function () {
old_init.apply(this, arguments);
// Do something extra
};
init.prototype = old_prototype;
}) ();
Another option could be:
var initial = function() {
console.log( 'initial function!' );
}
var iWantToExecuteThisOneToo = function () {
console.log( 'the other function that i wanted to execute!' );
}
function extendFunction( oldOne, newOne ) {
return (function() {
oldOne();
newOne();
})();
}
var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );
2017+ solution
The idea of function extensions comes from functional paradigm, which is natively supported since ES6:
function init(){
doSomething();
}
// extend.js
init = (f => u => { f(u)
doSomethingHereToo();
})(init);
init();
As per #TJCrowder's concern about stack dump, the browsers handle the situation much better today. If you save this code into test.html and run it, you get
test.html:3 Uncaught ReferenceError: doSomething is not defined
at init (test.html:3)
at test.html:8
at test.html:12
Line 12: the init call, Line 8: the init extension, Line 3: the undefined doSomething() call.
Note: Much respect to veteran T.J. Crowder, who kindly answered my question many years ago, when I was a newbie. After the years, I still remember the respectfull attitude and I try to follow the good example.
This is very simple and straight forward. Look at the code. Try to grasp the basic concept behind javascript extension.
First let us extend javascript function.
function Base(props) {
const _props = props
this.getProps = () => _props
// We can make method private by not binding it to this object.
// Hence it is not exposed when we return this.
const privateMethod = () => "do internal stuff"
return this
}
You can extend this function by creating child function in following way
function Child(props) {
const parent = Base(props)
this.getMessage = () => `Message is ${parent.getProps()}`;
// You can remove the line below to extend as in private inheritance,
// not exposing parent function properties and method.
this.prototype = parent
return this
}
Now you can use Child function as follows,
let childObject = Child("Secret Message")
console.log(childObject.getMessage()) // logs "Message is Secret Message"
console.log(childObject.getProps()) // logs "Secret Message"
We can also create Javascript Function by extending Javascript classes, like this.
class BaseClass {
constructor(props) {
this.props = props
// You can remove the line below to make getProps method private.
// As it will not be binded to this, but let it be
this.getProps = this.getProps.bind(this)
}
getProps() {
return this.props
}
}
Let us extend this class with Child function like this,
function Child(props) {
let parent = new BaseClass(props)
const getMessage = () => `Message is ${parent.getProps()}`;
return { ...parent, getMessage} // I have used spread operator.
}
Again you can use Child function as follows to get similar result,
let childObject = Child("Secret Message")
console.log(childObject.getMessage()) // logs "Message is Secret Message"
console.log(childObject.getProps()) // logs "Secret Message"
Javascript is very easy language. We can do almost anything. Happy JavaScripting... Hope I was able to give you an idea to use in your case.
as I understand it, you are trying to fetch the applications connected to the user account. You can do this by making a request on the API, I don't know if discord.js covers this part of the API
endpoint: https://discord.com/api/users/#me/connections
Request type: GET Header:
Authorization: "Beareryou token"
response: [
{...}
]
Use extendFunction.js
init = extendFunction(init, function(args) {
doSomethingHereToo();
});
But in your specific case, it's easier to extend the global onload function:
extendFunction('onload', function(args) {
doSomethingHereToo();
});
I actually really like your question, it's making me think about different use cases.
For javascript events, you really want to add and remove handlers - but for extendFunction, how could you later remove functionality? I could easily add a .revert method to extended functions, so init = init.revert() would return the original function. Obviously this could lead to some pretty bad code, but perhaps it lets you get something done without touching a foreign part of the codebase.

Categories

Resources