How can I call an object method using a function argument? [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I asked a similar question before... I wanted to know how to argue for the css property in a document.element.style.property=value. The solution was simple, and almost made sense --but clearly I didn't understand it entirely or I'd know trying the same solution for .element doesn't work.
Here is my code:
function appendElement(handle){
element=document[handle]('div');
document.body.appendChild(element);
}
This way I could choose to create a new element or shift an existing one based on id or class or index appearance or whatever. Of course even without knowing the correct way to do this, the code I have above looks wrong to me, but it's the best I can do without some assistance.
EDIT: Test case
/* The core instructions */
element=document.createElement('div');
document.body.appendChild(element);
/* the choosy version */
function appendElement(handle){
element=document[handle]('div');
document.body.appendChild(element);
}
appendElement(createElement);
element.innerHTML="third text";
/* SHOULD move the 'text' div under the 'third text' div*/
appendElement(getElementById('first'));
<div id="first">text</div>
<div>second text</div>

Edit
In this line appendElement(getElementById('first'));you are not passing a function as you want, you are passing the result of call undefined with the param 'first', because it can't find a function in that context or a global function called getElementById (so it will be undefined), furthermore your are trying to execute undefined passing it a string... this is going to raise an error, and in the case in which function existed (i.e you pass document.getElementById('first')), then you will be passing the returned value of executing that function instead of the function.
If you want to pass a function you should pass a function, thats is appendElement(document.getElementById), without calling it with an argument, but I think you are going to need to pass a selector to that function to accomplish what you are trying to do. So
the code will be something like this:
function appendElement(handle, selector){
element=handle.call(document, selector);
document.body.appendChild(element);
}
appendElement(document.getElementById, 'first');
<div id="first">text</div>
<div>second text</div>
call allows you to execute a function as a method and specify which object will be the receptor of that calling. Here is more info

I didn't understand your need.
But, if handle is equals to 'createElement', which is a property of document, your code will run.

Related

Stop a setInterval inside its callback [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
Does anyone have any idea how to stop an interval that is situated inside of a function once it's done doing its thing?
Here is what I mean:
function renderMessage(message) {
const renderInterval = setInterval(() => {
characterIndex++;
dealerMessage.innerHTML = `
${messages[message].slice(0, characterIndex)}
`;
if (characterIndex === messages[message].length) {
clearInterval(renderInterval)
}
}, 100);
}
As you can see, I'm trying to render out a message using this function. It does its job fine, but if I don't stop it, subsequent messages keep overriding themselves...
I've tested the if check and it is actually functioning inside the function, yet for some reason the clearInterval doesn't work.
Is there any way I can fix this, or do you recommend me to start from scratch?
Note: this method would be very handy for me, so, if possible, I would like to keep it.
I think your 'if' statement of clearInterval should be
if (characterIndex===message[message.length]){}
Also, I cannot see any initialization of the characterIndex variable. Please do inform if this worked or not.

Printing string in JavaScript is giving error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to print 2 strings. What is wrong here?
function alpha(name1, name2){
console.log(name1, name2);
}
<button onclick=alpha("Peter", "Jack")>ok</button>
Others have already told you that the issue is that the value of your onclick needs to be quoted and those quotes should not conflict with the quotes you are already using around your function arguments, but I have a different approach for you....
You really shouldn't be using inline HTML event attributes (i.e. onclick) in the first place. This is a 25+ year old technique that just won't die because it's easy to understand and most new developers just copy someone else's code and convert it to their needs. There are many reasons why this old technique should just fade away and instead, you should use the modern API for event binding, which is .addEventListener().
In your case, it's not obvious why a button would have function arguments hard-coded into it, but if that really is your use case, those should be stored as data-* attributes.
Here's your scenario, reworked into code from this century:
// Get a reference to the DOM element you need to work with
let btn = document.querySelector("button");
// Get the data-* into an array
let people = btn.dataset.people.split(",");
// Do the event binding in JavaScript, not HTML
// We'll set the click event to invoke an anonymous
// function that itself calls the real function and
// passes the proper arguments.
btn.addEventListener("click", function(){
alpha(people[0], people[1]);
});
function alpha(name1, name2){
console.log(name1, name2);
}
<!-- Notice that the data is held in a data-* attribute and
that the code to hook up the event is gone from the HTML. -->
<button data-people="Peter,Jack">ok</button>
You are wrongly defining the handler of onclick.
function alpha(name1, name2){
console.log(name1, name2);
}
<button onclick="alpha('Peter', 'Jack')">ok</button>
You are missing a pair of quotes.
<button onclick="alpha('Peter', 'Jack')">ok</button>
You need quotation marks around the function in HTML
function alpha(name1, name2){
console.log(name1, name2);
}
<button onclick="alpha('Peter', 'Jack')">ok</button>
Using Single quotes '' in the html instead of double will solve the issue. Also put quotes around the function
function alpha(name1, name2){
console.log(name1, name2);
}
<button onclick="alpha('Peter', 'Jack')">ok</button>

Adding item into an array with push function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
screenshot
Can someone verify where I went wrong?
addTodos parameter todos will override the global todos so just rename it to something else. see below example
var todos = ['1','2','3'];
function display() {
console.log(todos)
}
function addTodos(todo) {
todos.push(todo)
display()
}
addTodos('4')
The problem you are having with your code is, you created a global variable var todos and at the same time in your addTodos function you added an argument todos, the JavaScript is accessing your function argument not the global variable,
Now change the name of the global variable, to something like var myTodos to avoid conflicting
Hope this helps 😉
todos is a string not an array where error is occurring.
string type doesn't have push method. Also, local todos is found first in the local scope so it masks the array version.
Not sure whether you have realised, you are sending in an argument called todos. You are effectively overwriting the todos array that has been set previously. Replacing it with a new variable name would fix the problem
function addTodos(newTodo) {
todos.push(newTodo);
}

Which is the best way to validate the parameters received by a function [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Create: function (title, text, orientation, trigger, layout) {
$(this).attr
},
The trigger parameter must receive one of two very specific words: 'hover' or 'click' and I can't think of a good way to ease the implementation of this function.
I did think of some solutions:
I can try to validate the parameter once already inside in the function and return a 'console.info' right after breaking the execution in case a wrong parameter has been sent, informing the developer of his mistake
I could create a ENUM and provide it as an interface for the developer (which would still make the developer have to read it in order to use it properly)
Occurred me while typing this post that I could just set standard values for the options, hence they're optional.
I just don't know which one is the best approach in a situation like this. Can I assume that the developer that is willing to use the code MUST read the code to find the best way to implement it or (as I suppose) I should be concerned with validations like the ones I described? Also which one is the best?
Comparing straight up with strings is a common practice in javascript. ENUM-like structures, although easy to implement, are usually not very used because you either have to define your ENUM-like as globals or do something like:
application.enums.myObject.hover= 1;
application.enums.myObject.click= 2;
myObject= new application.constructors.MyObject();
myObject.create(title, text, orientation, application.enums.myObject.hover, layout)
In this manner only application is global, but typing application.enums.myObject is a pain.
How to handle the error:
Option 1: throw an exception:
Create: function (title, text, orientation, trigger, layout) {
if (trigger !== "hover" && trigger !== "click") {
throw "error: invalid parameter trigger";
}
},
This will crash your script unless you have a catch clause somewhere. In some cases crashing the party is better than not providing a way to know what is wrong. If you intend on catching these exceptions (instead of letting them just crash the script) I recommed doing it properly by making classes for your errors and such.
Option 2: Return null.
Create: function (title, text, orientation, trigger, layout) {
if (trigger !== "hover" && trigger !== "click") {
return null;
}
},
This approach works better if you are going to use the return value of the function. When debugging you will see "object has no property named X" error when trying to use the return value (or your value will be coerced into the "null" string if you use it as such).
Option 3: Quietly ignore the error and do nothing. Either your script will crash on its own or it will do nothing. Not recommended
Observations:
1 - do not use the console object in production code. It's not part of the standard and IE does not expose it to the web page unless you open the developer console
2 - do not start your function names with an upper case letter unless it's a function that should be called with the 'new' keyword (ie a constructor function).

Which strategy makes more sense in this jQuery plugin? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm making a jQuery plugin that displays alerts on the page. The plugin itself inserts the alert markup into the DOM. Since the jQuery way is to make everything return this to maintain chaining, I've run into an interesting issue I'd like feedback on. I'm trying to decide between the following two options.
Option One:
$("#content").alert('prepend', {type:'error', message:'This is an error'})
This looks pretty simple. An alert is prepended to the beginning of the #content DOM element. The problem is that it's unclear what is returned. It would make sense to return the alert element that was just created, but that kind of goes against the jQuery way.
Option Two:
$("<div>").alert({type:'error', message:'This is an error'}).prependTo("#content")
This way seems less clear and less intuitive, but it's more inline with the jQuery way of doing things, and it's clear what element is going to be returned.
So which options would you choose? My concern is that most users may not know that you can do $('<div>') to create a new element. On the other hand, I don't know of any well-known projects whose jQuery plugin methods return elements other than the elements they're invoked on, but perhaps there are. Thoughts?
I would just put it in the jQuery namespace (instead of on its prototype):
$.alert({type:'error', message:'This is an error'}).prependTo("#content");
In addition, you might consider asking for a selector/DOM node/jQuery object, instead of having the user prepend it themselves:
$.alert({
parent: '#content', // or $('#content') or document.getElementById('content')
type: 'error',
message: 'This is an error'
});
If your alert system is meant to be a popup-like or modal-like system, the user shouldn't have to specify a container. However, you can allow him to pass a container to insert your alertbox in:
$.alert({
type: 'error',
message: 'This is an error',
container: $(...) // Optional
});
It would return your plugin instance, or the alert container.
No, jQuery does not always return this. Chainability means only that you should return the instance itself if there's no result of your method.
For example, the clone() returns a new jQuery instance too; so there's nothing wrong with it. If you say "it's unclear", just document it, or rename the method to e.g. "$.fn.getAlert".
Yet, you must choose the signature of your method. The first option is like having a mandatory parameter for the container. If you like to make it optional, you might make the alert system a static method: $.createAlert(...) with an optional parameter.

Categories

Resources