Skip to content

Instantly share code, notes, and snippets.

@colevandersWands
Last active May 9, 2018 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colevandersWands/cd621df81e3f480e0ffa1e82c835d00a to your computer and use it in GitHub Desktop.
Save colevandersWands/cd621df81e3f480e0ffa1e82c835d00a to your computer and use it in GitHub Desktop.
binding object methods and reusing them
let controller = {
logic: {
add_async: function(num_1, num_2, cb) {
let result = num_1 + num_2;
if(typeof result == "number") {
cb(null, result);
} else {
cb(result);
}
}
},
view: {
display_result: function(result) {
console.log(result);
}
},
add_async_bind: function(num_1, num_2) { // this does
function cb(err, result) {
if (err) {
this.view.display_result(err);
} else {
this.view.display_result(result);
}
};
let bound_cb = cb.bind(this);
this.logic.add_async(num_1, num_2, bound_cb);
},
add_async_arrow: function(num_1, num_2) { // this does
this.logic.add_async(num_1, num_2, (err, result) => {
if (err) {
this.view.display_result(err);
} else {
this.view.display_result(result);
}
});
},
add_async_bad: function(num_1, num_2) { // this does
this.logic.add_async(num_1, num_2, function cb(err, result) {
if (err) {
this.view.display_result(err);
} else {
this.view.display_result(result);
}
});
}
};
controller.add_async_bind(3, 4);
controller.add_async_arrow(4, 5);
controller.add_async_bad(5, 6);
// https://goo.gl/PS5TaH
let source_object = {
prop: "source object",
print_prop: function() {
console.log(this.prop);
}
};
let bound_print = source_object.print_prop.bind(source_object);
console.log(typeof bound_print);
let new_object = {}
new_object.prop = "new object";
new_object.print_prop_bound = bound_print;
new_object.print_prop = function() {
console.log(this.prop)
};
source_object.print_prop();
new_object.print_prop();
new_object.print_prop_bound();
// https://goo.gl/9Xcb5W
binding and callbacks: https://thenewstack.io/mastering-javascript-callbacks-bind-apply-call/
a very thorough gist: https://gist.github.com/ytiurin/7e5f57809e3e6eeac616
from javascript.info: https://javascript.info/bind
you don't know js: https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures
let config = {};
config.controller = {};
config.controller.play = function() {
console.log(this.prop);
}
config.controller.prop = "manny";
let appPlay = config.controller.play.bind(config.controller);
console.log(appPlay());
// https://goo.gl/sVSh7V
// the full ttt_service: https://github.com/elewa-academy/APIs/blob/master/2-services/services-architecture-project/tictactoe-service/index.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment