Invoking javascript built-in objects constructor using call and apply - javascript

I am trying to invoke date object constructor on a click event using call/apply, but the constructor is not giving me the output. Here is the code snippet:
function invokeCommand(cmd) {
var parts='';
return cmd.call(this, parts);
}
YUI().use('node','event-base', function (Y) {
Y.on('domready', function () {
Y.one('#myconsole').on('submit', function () {
var cmd = Y.one('#cmd_input').get('value');
alert(invokeCommand(cmd));
});
});
});
Here I am trying to invoke the constructor and get the output or return the definition. Any thoughts?
I replaced the cmd.call with Date.call and I can able to see the output, but when Date is store in cmd var and invoked its not giving the output,
function invokeCommand(cmd) {
var parts='';
//return cmd.call(null);
return Date.call(null);
}
YUI().use('node','event-base', function (Y) {
Y.on('domready', function () {
Y.one('#jsconsole').on('submit', function () {
var cmd = Y.one('#cmd_input').get('value');
alert(invokeCommand(cmd));
});
});
});

Related

Passing parameters to a callback in javascript/nodejs

Hi I'm trying to understand callbacks in javascript and have come across this code here from a tutorial that I'm following:
var EventEmitter = require('events');
var util = require('util');
function Greetr() {
this.greeting = 'Hello world!';
}
util.inherits(Greetr, EventEmitter);
Greetr.prototype.greet = function(data) {
console.log(this.greeting + ': ' + data);
this.emit('greet', data);
}
var greeter1 = new Greetr();
greeter1.on('greet', function(data) {
console.log('Someone greeted!: ' + data);
});
greeter1.greet('Tony');
Now I notice that the greeter1.on function takes a callback with a parameter. However I'm not sure how this is implemented internally. I tried looking through the nodejs event.js file but I'm still confused. I am aware that there are ways around this specific implementation by using an anonymous function wrapping the callback with parameters but I want to understand how to use the same format as above.
tldr: How can I create my own function that takes a callback and a parameter in the same fashion as greeter1.on above.
Thank you
Your function needs to define a new property on the current instance with the callback passed as an argument, so it can be called later, like so:
function YourClass () {
this.on = function(key, callback) {
this[key] = callback;
}
}
// Usage
const instance = new YourClass();
instance.on('eventName', function (arg1, arg2) {
console.log(arg1, arg2);
});
instance.eventName("First argument", "and Second argument")
// logs => First argument and Second argument
Callback is just passing a function as a parameter to another function and that being triggered. You can implement callback fashion as below
function test(message, callback) {
console.log(message);
callback();
}
//Pass function as parameter to another function which will trigger it at the end
test("Hello world", function () {
console.log("Sucessfully triggered callback")
})
class MyOwnEventHandler {
constructor() {
this.events = {};
}
emit(evt, ...params) {
if (!this.events[evt]) {
return;
}
for (let i = 0, l = this.events[evt].length; i < l; i++) {
if (!params) {
this.events[evt][i]();
continue;
}
this.events[evt][i](...params);
}
}
on(evt, eventFunc) {
if (!this.events[evt]) {
this.events[evt] = [];
}
this.events[evt].push(eventFunc);
}
}
var myHandler = new MyOwnEventHandler();
myHandler.on('test', function (...params) {
console.log(...params);
});
myHandler.emit('test', 'Hello', 'World');

Jquery this returns empty object when calling from another function

i have a normal function which works and when i console log this it returns jQuery.fn.init [small.expand, context: small.expand
My function below:
jQuery(document).on('click', 'h3.shipping-name small.expand', function (e) {
var me = jQuery(this);
console.log(me);
var next = me.parent().next().next();
if (next.is(":hidden")) {
me.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
} else {
me.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
}
next.slideToggle();
});
But if i want to get it from another function like this:
var smallExpand = jQuery('h3.shipping-name small.expand');
smallExpand.on("click", function () {
expandDetails();
});
function expandDetails(e) {
alert("oki2");
var me = jQuery(this);
console.log(me);
var next = me.parent().next().next();
console.log(next)
if (next.is(":hidden")) {
me.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
} else {
me.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
}
next.slideToggle();
}
But it returns only empy object like this: jQuery.fn.init {}
What am i doing wrong?
Problem with your implementation is that this doesn't refers to current element it refers to window object thus the code doesn't work
You can use call() to set the this value
smallExpand.on("click", function (event) {
expandDetails.call(this, event);
});
Or, You could just pass the function reference to attach event handler
smallExpand.on("click", expandDetails);
Set the variable first out side your functions, then you can retrieve it for later.
var me;
Then
function first() {
me = $(this);
}
Now you can use the variable in another function
function thisorthat() {
$(‘.class’).val(me);
}
You are calling expandDetails as a static method.
as mentioned by #Satpal, you should just do smallExpand.on("click", expandDetails);.
this exists in the smallExpand.on("click", function() {}); scope, but once you call expandDetails(); it gets lost.

Calling a function in another function with AngularJS factory

I have an AngularJS factory that has multiple functions.
I want to call one of the functions inside the other function as shown below:
.factory("AppStart", function($cordovaSQLite) {
return {
init: function() {
var res = "hello";
console.log("in load start up page");
},
create_table: function() {
AppStart.init();
}
}
});
But I get the following error:
AppStart is not defined.
So how do I call the init() function in the create_table() function? I have tried just calling init(), but it doesn't work either.
To accomplish this, I recommend defining your functions with names, and then creating a service object with properties that refer to them, as I did below:
.factory("AppStart", function($cordovaSQLite) {
function init() {
var res = "hello";
console.log("in load start up page");
}
function create_table() {
init();
}
return {
init: init,
create_table: create_table
};
});

jQuery plugin function call to its own method?

I am using the following code below and essentially it takes an element as input (i.e.):
$(#someDiv).Calculator();
but the problem is that I want to call this plugin's function within itself, but I don't know how to get an object/handle to itself to call the function. caching off "this" does not have the proper reference.
(function ($) {
jQuery.fn.Calculator = function () {
var selectedObjects = this;
var control = $(selectedObjects[0])[0];
$("#btnCalculate").click(function(){
// this is where calculate needs to be called
someObject.calculate(...);
});
return {
calculate: function (value) {
// do some code
return selectedObjects;
}
};
}
})(jQuery);
Any ideas/direction would be of great help! Thank you all!
Try
(function ($) {
jQuery.fn.Calculator = function () {
var selectedObjects = this;
var control = $(selectedObjects[0])[0];
$("#btnCalculate").click(function(){
// this is where calculate needs to be called
calculator.calculate(...);
});
var calculator = {
calculate: function (value) {
// do some code
return selectedObjects;
}
};
return calculator;
}
})(jQuery);

JavaScript / jQuery scope

Hi I'm extending an existing plugin to use static JSON rather than load it from the server. This is a trimmed down version of the extension:
(function ($) {
$.fn.MyExtension = function (options) {
return this.each(function () {
if (opts.load_Json) {
$.get("", function (result) {
fromJson(opts.load_Json)
});
}
var fromJson = function (json) {
// json stuff..
}
});
});
If I remove the $.Get and call fromJson directly without the call back I get an error saying that fromJson is not defined. This must be some form of scope issue but I cant work it out?
This isn't scope. This is timing.
A function isn't assigned to fromJson until the end of the anonymous function you pass to each.
If you call it from your get callback, then that assignment will happen before the HTTP response comes back and the function fires.
If you call it directly, then it just doesn't exist yet.
Either reorder:
return this.each(function () {
var fromJson = function (json) {
// json stuff..
}
if (opts.load_Json) {
$.get("", function (result) {
fromJson(opts.load_Json)
});
}
});
Or use a function declaration (which will be subject to hoisting):
return this.each(function () {
if (opts.load_Json) {
$.get("", function (result) {
fromJson(opts.load_Json)
});
}
function fromJson (json) {
// json stuff..
}
});

Categories