make document.getElementById into a var - getelementbyid

Is there any way you can make "document.getElementById" into a variable?
I want to be able to write
myVariable("id").innerHTML = (blabla);
instead of
document.getElementById("id").innerHTML = (blabla);
Pardon me if this has been answered. I've sought and found nil! newbie

You can wrap the output into another function
var shortID = function(id) {
return document.getElementById(id);
}
shortID('myID').innerHTML = "...";

To provide a simpler way to call common code, you can just define your own function like migvill suggests.
To answer the question directly though, you can point to the document.getElementById function (or any other function) using a variable. This is as obvious as you could imagine:
var myVariable = document.getElementById;
The problem with this is that the function itself (the object that myVariable now points to) is not intrinsically linked to the document object that it is designed to work with. When you write document.getElementById("id"), the document is automatically given to the function, but with myVariable you would need to specify it. This can be done using the call function:
myVariable.call(document, "id").innerHTML = "blabla";
And finally, the bind function can be used to create a new function that automatically links the given object (this has essentially the same effect as defining your own wrapper function):
var newFunc = myVariable.bind(document);
newFunc("id").innerHTML = "blabla";

Related

p5.js - When to declare variables using var vs this.varName

I'm still figuring out how to use p5.js. In regular java you have to declare each variable using its data type, ex. int foo = 0.
In p5, I know you can just use var foo but you can also declare variables using this.foo. If someone could clarify when is the proper time to use var and when i can use this, that would be very helpful.
For example, if I want to declare a variable inside a method, should i use var foo = thing or could I declare it using this.foo = thing? What should I use when declaring global variables or when referring to objects passed into methods?
Thanks!
First of all, p5 is not a language, it is a Javascript library, you are coding in Javascript, not p5.
Coming to your question, if you want to use some function as a data type, similar to a class in java, and want all the "instances" of that to have their own different variables, you use this. If they are just variables you use in someway but don't need to be specific for each instance, or if the function is not a constructor function and is not to be used as a data type, you will just use var then.
Again, there is no class stuff in javascript, you will have to write what is called a constructor function in order to "simulate" a java class, but be aware that a constructor function should not return anything. Here is an example of car class in java:
class car {
int speed = ___;
String model = ___;
static int numOfWheels = ___;
}
This is what it will look like in javascript (a constructor function):
function car() {
this.speed = ____;
this.model = ____;
var numOfWheels = ___;
}
If you declare a variable without this, it can be roughly compared to a static variable in a java class in the sense that it will be constant among all the instances.
So basically, at least in most cases, you will use this.varName usually inside constructor functions, i.e., functions that you will use to construct objects.
What should I use when declaring global variables or when referring to objects passed into methods?
Global variables will almost always be var something = something. When referring to objects passed into functions, just use the dot notation to refer to its properties like passedObject.someProperty
I would recommend you to learn Javascript before jumping into p5 directly, here are some resources that I found useful when I started learning Javascript-
w3 School
JavaScript Info Website
TheNewBoston

How can I reuse code between Javascript macros and minimize work done within the macros?

I currently have two macros that are part of a (very limited-audience) plugin I'm developing, that both look basically like:
(function(){
exports.name = "name";
exports.params = [
{name: "value"}
];
function get(tiddler) {
// return some contents of some tiddler fields according to some rule
}
function parse(data) {
// convert string to some kind of useful object
}
function logic(x, y) {
// determine whether the two objects correspond in some way
};
function format(data, title) {
// produce WikiText for a link with some additional decoration
};
exports.run = function(value) {
value = parse(value);
var result = [];
this.wiki.each(function(tiddler, title) {
var data = get(tiddler);
if (data !== undefined && logic(value, parse(data))) {
result.push(format(data, title));
}
});
return result.join(" | ");
};
})();
So they're already fairly neatly factored when considered individually; the problem is that only the core logic is really different between the two macros. How can I share the functions get, logic and format between the macros? I tried just putting them in a separate tiddler, but that doesn't work; when the macros run, TW raises an error claiming that the functions are "not defined". Wrapping each function as its own javascript macro in a separate tiddler, e.g.
(function(){
exports.name = "get";
exports.params = [
{name: "tiddler"}
];
exports.run = function(tiddler) {
// return some contents of some tiddler fields according to some rule
}
})();
also didn't help.
I'd also like to set this up to be more modular/flexible, by turning the main get/parse/logic/format process into a custom filter, then letting a normal filter expression take care of the iteration and using e.g. the widget or <> macro to display the items. How exactly do I set this up? The documentation tells me
If the provided filter operators are not enough, a developer can add
new filters by adding a module with the filteroperator type
but I can't find any documentation of the API for this, nor any examples.
How can I share the functions get, logic and format between the macros?
You can use the Common/JS standard require('<tiddler title>') syntax to access the exports of another tiddler. The target tiddler should be set up as a JS module (ie, the type field set to application/javascript and the module-type field set to library). You can see an example here:
https://github.com/Jermolene/TiddlyWiki5/blob/master/core/modules/widgets/count.js#L15
I'd also like to set this up to be more modular/flexible, by turning the main get/parse/logic/format process into a custom filter, then letting a normal filter expression take care of the iteration and using e.g. the widget or <> macro to display the items. How exactly do I set this up?
The API for writing filter operators isn't currently documented, but there are many examples to look at:
https://github.com/Jermolene/TiddlyWiki5/tree/master/core/modules/filters

Convert: "preg_replace" -> "preg_replace_callback"

I'm trying to update my code but I'm stuck at this codeline.
How do I proceed to convert this to preg_replace_callback?
$buffer = preg_replace("#§([a-z0-9-_]+)\.?([a-z0-9-_]+)?#ie","\$templ->\\1(\\2)",$buffer);
Here is the process of converting preg_replace (with the e modifier) to preg_replace_callback. You create a function that will act on all of the matches that it finds. Normally this is pretty simple, however with your case it is a little more complex as the function returns the value of an object. To accommodate this, you can use an anonymous function (a function without a name) and attach the USE keyword with your object to it. This can be done inline, however for the sake of clarity, I have made it its own variable.
Take a look at this portion of the complete code below:
$callback_function = function($m) use ($templ) {
I created a variable named callback_function that will be used in the preg_replace_callback function. This function will be fed each match as the variable $m automatically. So within the function you can use $m[1] and $m[2] to access the parts of the expression that it matched. Also note that I've attached the $templ variable with the USE keyword so that $templ will be available within the function.
Hopefully that makes sense. Anyway, here is the complete code:
<?php
// SET THE TEXT OF THE BUFFER STRING
$buffer = 'There are a bunch of §guns.roses growing along the side of the §guns.road.';
// THIS IS JUST A SAMPLE CLASS SINCE I DO NOT KNOW WHAT YOUR CLASS REALLY LOOKS LIKE
class Test {
// FUNCTION NAMED 'guns' WITH A SPACE FOR A PARAMETER
public function guns($info) {
return '<b>BLUE '.strtoupper($info).'</b>';
}
}
// INSTANTIATE A NEW 'Test' CLASS
$templ = new Test();
// THIS IS THE FUNCTION THAT YOUR CALLBACK WILL USE
// NOTICE THAT IT IS AN ANONYMOUS FUNCTION (THERE IS NO FUNCTION NAME)
$callback_function = function($m) use ($templ) {
return $templ->$m[1]($m[2]);
};
// THIS USES PREG_REPLACE_CALLBACK TO SUBSTITUTE OUT THE MATCHED TEXT WITH THE CALLBACK FUNCTION
$buffer = preg_replace_callback('/§([a-z0-9-_]+)\.?([a-z0-9-_]+)?/i', $callback_function, $buffer);
// PRINT OUT THE FINAL VERSION OF THE STRING
print $buffer;
This outputs the following:
There are a bunch of <b>BLUE ROSES</b> growing along the side of the <b>BLUE ROAD</b>.

Rewriting .each() loop as for loop to optimize, how to replicate $(this).attr()

I running into some performance issues with a jquery script I wrote when running in IE so I'm going through it trying to optimize any way possible. Apparently using for loops is way faster than using the jQuery .each method. This has led me to a question regarding the equivalent of $(this) inside a for loop. I'm simplifying what I'm doing in my loop down to just using an attr() function as it gets across my main underlying question.
Im doing this with each(simplified)
var existing = $('#existing').find('div');
existing.each(function(){
console.log($(this).attr('id'));
});
And I've tried rewriting it as a for loop as such:
var existing = $('#existing').find('div');
for(var i = 0;i < existing.length;i++)
{
console.log(existing[i].attr('id'));
}
Its throwing an error saying:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'attr'
You need existing.eq() to get jQuery object, existing[] gives you DOM object. The function attr() should be called with jQuery object but not with DOM (javascript) object.
var existing = $('#existing');
for(var i = 0;i < existing.length;i++)
{
console.log(existing.eq(i).attr('id'));
}
You can use each to get index without for loop.
existing.each(function(index, item){
alert(index);
alert(item);
});
To get the id of an element just do
existing[i].id
Note that you jQuery loop would also be faster as
existing.each(function(){
console.log(this.id);
});
More generally, you should not use attr('id'), especially if you're concerned by performances, as a DOM object has a property id.
.I have to ask you a question before I give my answer, why would you need to perform a loop on a single element, #existing is an Id not, therefore it's a unique element on your page.
you could simply do
$('#existing').prop('id');
In case your have more than one elements, you should be using a class or another attribute, if that is the case, you could use the following:
$.each('.existing',function(index,item){
console.log(item.prop('id'));
});
better use prop() insted of attr() as attr is deprecated

What is action ID in Photoshop script?

I read a tutorial of photoshop scripting,
and I can't understand this line.
//get action ID
cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };
I think these codes are call Photoshop actions,
but I don't have any references, so
I can't really understand how to use these.
Why are they need and How to use these?
Well, the code you posted creates convenient aliases for the charIDToTypeID and stringIDToTypeID functions. Those functions simply convert strings to an enumeration value of type PSConstants. For instance,
CharIDToTypeID("BD1") //returns 1111765280 which corresponds to PSConstants.phEnumBitDepth1
See http://www.pcpix.com/Photoshop/

Resources