Angular 2 Subscribe using arrow functions vs named function variables using bind - javascript

When subscribing to Http Observable objects most tutorials use arrow functions :
this.myService.getItems.subscribe(
(data) => // do something,
(errors) => //handle errors);
Why don't use function variables instead to have cleaner code :
this.myService.getItems.subscribe(this.extractData.bind(this), this.handleErrors.bind(this));

It depends on your style. Using (data) => { do something} looks a bit confuse first time, but the more you use it, the more you are comfortable. You'll like it and don't want to use this.extractData.bind(this)

Related

difference in function call

I was trying to understand how the respective function call work when we use it in React
Suppose we have two functions like this
const something = () => {
//something
}
function something1 () {
//something
}
Till now, I have seen them being called in three different ways
like
{this.something}
this.something()
(() => something)
So my primary question is how are they different? like when being called and if there is any other way to call them (not mentioned here)?
this.something will not properly call a function. this.something() is the ideal way to call it because it's the most performant! () => this.something() actually triggers a re-render every time the function is called because you're creating a new function (you're literally wrapping this.something() within an empty arrow function). That being said, both are useful in different instances. When in doubt, go with this.something().

How do arguments in publish/subscribe pattern work?

In one place we use eventEmitter to generate events. Actually it's the very common way.
eventEmitter.emit('started', data, date);
In the other place we try to catch it. Everything is pretty clear when using arrow functions. 'data' and 'date' are passed to the function as arguments
someInstanse.event.on('started', (data, date) => {
//crazy stuff here
})
But how this notaion in fact works? We determine 3 args with emitter and now we really have only event string and a function instead
someInstance.event.on('started', function(data, date) {
});
I suppose that before adding arrow functions it was the only way to call anonymous functions
This is the typical publish/subscribe design pattern. And it is really determined by how the emit and how subscribers respond to the event are implemented under the hood.
Basically, in the publish function, you want to call every subscriber(on) functions, provided with the information with publish(emit). Below is just some pseudo-code.
function publish(type, ...args) {
// for each of the subscribers of that type
for (let i = 0; i < pubsub[type].length; i++) {
// you could do (this provides the listener with type)
subscribers[i](type, ...args)
// or you could do (the subscriber doesn't know the type)
subscriber[i](...args)
}
}
I wrote a minified pub/sub pattern in github, if you want to take a look. I think it's extremely helpful to help you understand this issue.
https://github.com/thomasyimgit/pubsub/blob/master/index.js

jQuery (or clean JS) - add callback to any function-parameter

What I want looks like this:
function bindFunctions(bindFunction, callbackFunction) {
// Add binding so that I can call the callbackFunction if the bindFunction is called
}
function log(message) {
console.log(message);
}
function notifyUser() {
alert('Something');
}
bindFunctions(log, notifyUser);
log('Error'); // Now the notifyUser-functions should be called and "Something" printed to the alert-box
bindFunctions($('.element').click, function() {/* CODE */}); // Or this: but I don't know if this is even possible because this is not the event-function but the binding-function of the click-event
Important: I have no influence on the bindFunction so it's not possible to implement a trigger there.
It's an attachment of a callback on any kind of existing function. Do you know how or if this is possible?
I believe you're looking at it the wrong way. What you need is some good old dependency inversion. Whatever code needs log has to receive it from a higher-level component (e.g. the composition root of your application). You're then free to implement a straightforward wrapper that calls notifyUser and inject it instead of the actual log.
I've linked some articles taking an OO perspective, but feel free to translate to a more functional model (the approaches are equivalent). In your case, you're using closures (which are, under a certain light, "equivalent" to objects with a single anonymous method).
The way you have to do to add a callback to a function is this:
var foo = function(number, callback){
number += 2;
callback(number);
}
foo(2, function(result){
window.alert(result)
});
https://jsfiddle.net/6dpz88md/
Good luck

Binding to original this in JavaScript

I have an object that is as follows:
{ except: player => ({ send :player.getSocket().broadcast.emit }) }
However this means that the this in the emit function is not the one it expects it to be (the broadcast object).
So I can do:
{ except: player => ({ send : (msg, data) => player.getSocket().broadcast.emit(msg, data) }) }
But this is ugly, especially if the arguments change.
So the alternative is:
{ except: player => ({ send : (t = player.getSocket().broadcast).emit.bind(t) }) }
But is there a tidier way of doing this, of assigning a function to an object while maintaining it's this as it's parent object.
You can specify who this will be by calling the function with apply or call. The first parameter to these methods will be this within the body of the function.
Using bind in order to maintain the scope of this is actually a good solution to your problem, the way I see it, it makes the code a lot more understandable because you can know to what object the function actually belongs, by using apply or call, when you read the code you wont know to what this the function/method belongs. As far as i know, bind is a pretty good solution to your problem here.

Calling helper functions from within template.rendered in Meteor.js, error in 1.0, fine in 0.9.3

In an effort to avoid repeating code I found it useful to have helper functions that could be called from within a foo.rendered function (for instance). Why is this possible in 0.9.3 of Meteor, but throws an error in 1.0 ?
Template.foo.helpers({
'fooFn' : function(){
return "something"
}
});
Template.foo.rendered = function(){
var something = Template.foo.fooFn();
}
Should I change the syntax in foo.rendered (am I calling it wrong?) or maybe use a different approach entirely (set up functions outside of the helpers({}) and rendered() and call those? or set this up as a registered helper function?
It looks like it is possible as of Meteor 1.0.3.1 to find and call helper functions, although it is clear it's not supposed to be used like this.
Still it can be done:
Template.foo.__helpers[" fooFn"]()
Please notice the leading space for the function name.
The other way of dealing with this is attaching a function to a global namespace, then calling that from somewhere else in your code, as user3557327 mentioned.
Additionally you can use:
Template.registerHelper('myHelper', function (){return 'Look At Me!'})
to register a global helper, and call it explicitly using:
UI._globalHelpers['myHelper']()
I think this would be a better method: How to use Meteor methods inside of a template helper
Define a function and attach it to the template. Call that function from rendered, as well as your template helper. Like MrMowgli said, you probably aren't "supposed" to call template helpers from within the .js file, only from the ...that could probably break in the future.
For example define a function and attach it to the tamplate:
Template.Play.randomScenario = function () { // HACK HACK HACK }
and then call it from your lifecycle method
Template.Play.created = function () {
Template.Play.randomScenario();
};
scenario: function () {
return Template.Play.randomScenario();;
},
I had the same problem and this is the solution I used. Hope that helps.

Categories

Resources