How to create a object with prop as function and attribute - javascript

I need to create a fake object that accepts the following calls:
object.loading()
object.loading.close()
I've tried to create something like:
obj = {
loading: function() {
close: function() {
}
}
}
But it doesn't work.

This is one approach:
const object = {};
object.loading = function() {console.log('loading')};
object.loading.close = function() {console.log('closing')};
object.loading();
object.loading.close();

If you need something to be both a function and have its own methods, you need to create the function and then assign the methods to it afterward. What you tried above is to put close in the body of the function, and that won't work.
Try this:
var obj = {
loading: function () {
}
};
obj.loading.close = function () {};
obj.loading(); // no error
obj.loading.close(); // no error

Related

is there a good way to call methods dynamically in js?

I have 2 js functions:
function onRegionMouseOver()
{
}
function onRegionMouseOut()
{
}
Is it possible to call these js functions dynamically doing something like this?:
var type = 'Out'
//the following line would exec onRegionMouseOut() above:
call(onRegionMouse[type]())
You can use this:
var onRegionMouseHandlers = {
out: function () {},
in: function () {}
}
// and using like this
var whatToUse = 'in';
// use
onRegionMouseHandlers[whatToUse]()
Also, you can remove your which choose what function have to be called. You can just add two handlers to two different events.
You can define the functions as properties of an object, use bracket notation to call the function.
const methods = {
onRegionMouseOver() {console.log("Over")},
onRegionMouseOut() {console.log("Out")}
}
let fn = "onRegionMouse";
let type = "Out";
methods[`${fn}${type}`]();
type = "Over";
methods[`${fn}${type}`]();
without template literal or let
var methods = {
onRegionMouseOver: function onRegionMouseOver() {console.log("Over")},
onRegionMouseOut: function onRegionMouseOu() {console.log("Out")}
}
var fn = "onRegionMouse";
var type = "Out";
methods[fn + type]();
type = "Over";
methods[fn + type]();
You can do something like that, provided you declare an object that contains the functions.
var onRegionMouse = {
Out: onRegionMouseOut,
Over: onRegionMouseOver
};
Now you can just do
var type = 'Out';
onRegionMouse[type]();
what about:
var myFunctions = {
out: function onMouseOut()...,
enter: function onMouseEnter()...
}
You can call it now with myFunctions[ "out" ] ()

Use of debounce on Ext 3.4 framework

I want to implement the debounce function on Ext.Button, so I extended it and override the onClick function, like this:
MyButton = Ext.extend(Ext.Button, {
onClick: function(e) {
var that = this;
var args = e;
clearTimeout(this.timeoutDebounce);
this.timeoutDebounce = setTimeout(function(){
MyButton.superclass.onClick.apply(that, [args])
}, this.debounce);
}
});
Debounce is a parameter passed on the x-type declaration.
The problem here is that the "args" parameter I'm passing to onClick has changed when it's called from "click" to "mouvemove" and it doesn't fire the events it should.
Is there a way to record the "e" parameter received in the function to pass to onClick on superclass?
The function passed to setTimeout must be wrapped in order to keep the value presented in current scope:
function createCallback(args) {
return function() {
MyButton.superclass.onClick.apply(that, [args]);
}
}
Also, e is passed by reference, so you need to create a copy of it. Using ExtJS, you can use Ext.apply method:
Ext.apply({}, e);
The full code should be:
var MyButton = Ext.extend(Ext.Button, {
onClick: function(e) {
var that = this;
function createCallback(args) {
return function() {
MyButton.superclass.onClick.apply(that, [args]);
// you can also use call since you know the arguments:
// MyButton.superclass.onClick.call(that, args);
}
}
clearTimeout(this.timeoutDebounce);
var copy = Ext.apply({}, e);
this.timeoutDebounce = setTimeout(createCallback(copy), this.debounce);
}
});
You should clone the object:
var args = Ext.apply({}, e);
this.timeoutDebounce = setTimeout((function(args){
return function(){MyButton.superclass.onClick.apply(that, [args])};
})(args), this.debounce);

I wanted to make a javascript library function is not working

I wanted to call the run function that should call the other and action will be done on the base of element_id
NGL = {}
NGL.SceneBuilder = function() {
var yamlFile = 'http://example.com/main.yaml'
var parseYaml = function() {
}
var buildScene = function() {
// other code
simulationStarted(element_id);
}
return {
run: function(element_id) {
parseYaml();
buildScene(element_id);
}
}
}
NGL.SceneBuilder.run('#someid');
You're not executing your factory so NGL.SceneBuilder is a function, not an object having the run property. Call the function :
NGL.SceneBuilder = (function() {
...
})(); // <<===
Note also that you forget to declare the element_id parameter in buildScene but maybe is it just for the question.

How do I call a nested JavaScript function properly

I'm trying to set up function a nested function that I can call throughout my script, but I keep getting "error undefined is not a function". Perhaps someone can help me with how to do this correctly.
First I set global my variables:
var trigger = document.getElementById('trigger');
var subject = document.getElementById('subject');
Then I create a show/hide function:
var toggleVis = function() {
function showSomething() {
trigger.classList.add("active");
subject.classList.add("active");
}
function hideSomething() {
trigger.classList.remove("active");;
subject.classList.remove("active");
}
}
Then I set my event listener:
trigger.addEventListener('click', function() {
if ( subject.classList.contains("active") ) {
toggleVis.hideSomething();
}
else {
togglePicker.showPicker();
}
});
The reason I'm trying to do it this way is that there will be other triggers for subject on the page that will need access to the show/hide functions.
You can't access the functions inside the function, they are out of scope, you could attach them as properties to the wrapping function, but it looks like you just need an object
var toggleVis = {
showSomething: function() {
trigger.classList.add("active");
subject.classList.add("active");
},
hideSomething: function() {
trigger.classList.remove("active");;
subject.classList.remove("active");
}
}
Your togleVis variable is a function and not an object so you can't do toggleVis.hideSomething(). Try updating your code to :
var toggleVis = (function() {
return {
showSomething : function () {
trigger.classList.add("active");
subject.classList.add("active");
},
hideSomething : function () {
trigger.classList.remove("active");;
subject.classList.remove("active");
}
};
}());
With this toggleVis is now an object with two properties showSomething and hideSomething functions.

Writing a callback like the jQuery on click

In jQuery you can use callbacks like this:
$('#btn').on('click', function() {
// code
});
How can I write something just like i.e.
foo.on('bar', function() {
// code
});
foo.on('buzz', function() {
//code
});
?
Thanks.
It is a valid statement in jQuery, to invoke the method you need to trigger the event using .trigger(eventname)
like
foo.trigger('foo')
The following article will be helpful
How to Create Custom Events in jQuery
http://www.sitepoint.com/jquery-custom-events/
jQuery’s .trigger method is the key. You can trigger an event with a new type name and arbitrary data at any point, e.g.
$.event.trigger({
type: "newMessage",
message: "Hello World!",
time: new Date()
});
Handlers can now subscribe to “newMessage” events, e.g.
$(document).on("newMessage", newMessageHandler);
Like that:
var eventBus = function () {
var supportedEvents = ['bar', 'buzz'];
var subscribers = {};
for (var i = 0; i < supportedEvents.length; i++) {
subscribers[supportedEvents[i]] = [];
}
return {
on: function (event, action) {
subscribers[event].push(action);
},
trigger: function (event) {
var funsToCall = subscribers[event] || []; // empty array if unsupported event
for (var i = 0; i < funsToCall.length; i++) {
funsToCall[i](); // calling a function
}
}
}
}
And then you call the eventBus function to get an object that will be your foo:
var foo = eventBus();
foo.on('bar', function () {
console.log('bar');
});
foo.on('buzz', function () {
console.log('buzz');
});
foo.trigger('bar'); // prints 'bar' to the console
foo.trigger('buzz'); // prints 'buzz' to the console

Categories

Resources