AngularJs destructuring $location - javascript

Instead of using:
const ref = $location.protocol() + '://' + $location.host();
i try to do it like this:
const { protocol, host } = $location;
const ref = protocol() + '://' + host();
but it does not seem to work. ( protocol() is not returning anything, same for host() )
However, if I try something like this:
const loc = {
protocol: function(){
return 'http';
},
host: function(){
return 'example.com';
},
};
const { protocol, host } = loc;
document.write(protocol() + '://' + host());
it works. Any ideea why?
Ps. Some sample here, just uncomment the second line and it would not work anymore.

The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from
objects, into distinct variables.
You loose reference to this when you de-structure methods,$location.protocol and protocol refer to different this
let a = {
myName : 'my name',
nameLogger(){
return this.myName
}
}
let {nameLogger} = a
console.log( 'Hello ' + nameLogger())
nameLogger = nameLogger.bind(a)
console.log( 'Hello ' + nameLogger())

Related

How to create this kind of Object in Javascript

I'm using Node.js to access this hdPrivateKey but it look like
<hdPrivateKey...>
Not look like normal JS object.
And console.log(address) looks like
<Address: 19o9ghmkUrNVf4d57tQJuUBb2gT8sbzKyq, type: pubkeyhash, network: livenet>
console.log(Object.keys(address)) look like
[ 'hashBuffer', 'network', 'type' ]
Why the key inside address are different?
var bitcore = require('bitcore');
var HDPrivateKey = bitcore.HDPrivateKey;
var hdPrivateKey = new HDPrivateKey();
console.log(hdPrivateKey)
var retrieved = new HDPrivateKey(hdPrivateKey);
var derived = hdPrivateKey.derive("m/0");
var derivedByNumber = hdPrivateKey.derive(1).derive(2, true);
var derivedByArgument = hdPrivateKey.derive("m/1/2");
var address = derived.privateKey.toAddress();
console.log(Object.keys(address))
console.log(address)
// obtain HDPublicKey
var hdPublicKey = hdPrivateKey.hdPublicKey;
The behavior you're seeing is because the object has its own inspect property which is a function and returns a string. When console.log sees that it's logging an object, it looks for that function and uses it if available. So on Node, this logs <foo>:
const o = {
inspect() {
return "<foo>";
}
};
console.log(o);
That's all that the HDPrivateKey object is doing.
If you want to properly inspect the object, use a debugger. Alternately, use utils.inspect with customInspect set to false.
In Node.js, a console.log call the function inspect of the object. In the bitcore-lib there is this method :
HDPrivateKey.prototype.inspect = function() {
return '<HDPrivateKey: ' + this.xprivkey + '>';
};
And this method:
Address.prototype.inspect = function() {
return '<Address: ' + this.toString() + ', type: ' + this.type + ', network: ' + this.network + '>';
};

Using Firebase, how can I pass a created key to another function?

I'm creating a multiuser app and wanted to use keys to product user information. I created a function that updates the child of a database with a generated key. The following function behaves correctly:
unlist(list) {
var postData = {
state: "unlisted",
};
var newPostKey = firebase.database().ref().child('foods').push().key;
var updates = {};
updates['foods' + '/' + list.$key + '/' + 'state' + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);}
I have a separate function that works similarly to this:
changestate(item) {
var postData = {
state: "listed",
};
var newPostKey = firebase.database().ref().child('foods').push().key;
var updates = {};
updates['foods' + '/' + item.$key + '/' + 'state' + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);}
In order to make this work correctly, the key that is created from unlist(list) needs to correspond to var newPostKey in changestate(item) and vice versa. How can I make this work?
cfoster5. What I have understood from your question is that the newPostkey from the unlist function should be passed to the changeState(item) function if that's what you want means you can do that by calling promise in the
firebase.database().ref().update(updates).then(function(){
// You can call changestate function and pass the function like below
_changestate(item,newPostkey);
});
and in your changestate function,
changestate=function(item,passedkey){
var newPostKey = passedkey;
}
See my jsfiddle sample

A proper way to declare an JavaScript Options-Object?

i wanted to access an API which responses with some JSON. Therefore I want to configure an 'options' object, which stores all the data which are needed to access the api (url, tokens, id, etc.).
The following version works:
var Options = function (token, id) {
this.token = token;
this.id = id;
this.host = 'http://super-cool-api.com/';
this.path = 'api/fetch/id/';
this.url = '' + this.host + this.path + this.id + '?token=' + this.token
};
var options = new Options('abc', 3);
// options.url = "http://super-cool-api.com/api/fetch/id/3?token=abc"
Basically 'options.url' is all I want. But I've tried to declare a more comprehensive form for the 'options' object, like this:
var options = {
token : 'abc',
id : 3,
host : 'http://super-cool-api.com/',
path : 'api/fetch/id/',
url : '' + this.host + this.path + this.id + '?token=' + this.token
};
// options.url = "undefinedundefinedundefined?token=undefined"
Okay, I understood that I have to access the values in options.url somehow else. But how? Is this even common practice?
What about my first solution? Is it recommended to do it this way?
Regards,
Christoph
Unfortunately this in your second example points to the object that contains the code, i.e. NOT options, that is why the variables are undefined. The first solution is fine, as would be:
function makeOptions(token, id) {
var host = 'http://super-cool-api.com/',
path : 'api/fetch/id/';
return {
token: token,
id: id,
host: host,
path: path,
url: '' + host + path + id + '?token=' + token
};
}
Choose what suits you best.
Both ways you show are OK ways of doing this, as for the most accepted / standard way of doing it, I wouldn't really know.
Here is an example of how to get the Second Option you showed to work correctly :
Set the url of options to be a function that builds the URL and returns it.
var options = {
token : 'abc',
id : 3,
host : 'http://super-cool-api.com/',
path : 'api/fetch/id/',
url : function() {
return '' + this.host + this.path + this.id + '?token=' + this.token;
}
};
And then you can retrieve the value using the following : var testUrl = options.url();
Here is an example JSFiddle for both of your examples, plus my example (Option 3)

window.location.url Javascript

I'm splitting the current url into pieces but I'm doing something wrong with this part to get the current url. How can I solve this?
var url = window.location.url;
I'm trying to get the current url from the page. This is my function
function split(){
var url = window.location.url; // This part is not correct
var firstSplit = url.split('?')[1];
var name = firstSplit.split('&')[0];
var age = firstSplit.split('&')[1];
var parName = name.split('=')[0];
var nameName = name.split('=')[1];
var parAge = age.split('=')[0];
var ageAge = age.split('=')[1];
document.getElementById("nameId").innerHTML=naamName;
document.getElementById("ageId").innerHTML=leeftijdAge;
}
Use href:
window.location.href
For example running it on current SO page gives:
console.log(window.location.href);
this:
http://stackoverflow.com/questions/10783322/window-location-url-javascript
Add the following script to a page; it will display all the properties of the page's url:
document.write("<li>location.href = " + location.href);
document.write("<li>location.protocol = " + location.protocol);
document.write("<li>location.host = " + location.host);
document.write("<li>location.hostname= " + location.hostname);
document.write("<li>location.port = " + location.port);
document.write("<li>location.pathname = " + location.pathname);
document.write("<li>location.hash = " + location.hash);
document.write("<li>location.search = " + location.search);
better answer found here: https://gist.github.com/jlong/2428561
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.host; // => "example.com:3000"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.hash; // => "#hash"
parser.search; // => "?search=test"
You can access different parts of the URL directly by using different properties on window.location.
The full URL is window.location.href, but you seem to be more interested in the query string (the part after the question mark) which you can access with window.location.search
A list of other properties is can be found in the MDN article about window.location.
Try
var url = window.location.href;
Or
var url = document.URL;
and I think Please use function name something different then split because it is a function of PHP and may be reason of problem.
thanks
I'm not exactly sure what yo are trying to do after you break the URL into parts but here is how you can get the current URL and put them into variables. You can put them back together however you like latter. Source: [http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/][1]
var urlNow = window.location.pathname.split('/');
var itNow0 = urlNow[0];
var itNow1 = urlNow[1];
var itNow2 = urlNow[2];
var itNow3 = urlNow[3];
alert(itNow0+ ' ' +itNow1+ ' ' +itNow2+ ' ' +itNow3);

jQuery/Javascript - reload current page with an appended querystring?

I've got a dropdown menu on my form, which when something is selected I need to reload the current page, but with an appended querystring.
How would I go about doing this?
This is an old question but it came up first in google search results.
The solution I went with is similar to jAndy's.
window.location.pathname gives me the page's url without the query string.
I'm then able to build the query string with "?"+$.param({'foo':'bar','base':'ball'}) which I then append to the pathname and set to window.location.href.
window.location.href = window.location.pathname+"?"+$.param({'foo':'bar','base':'ball'})
var params = [
"foo=bar",
"base=ball"
];
window.location.href =
"http://" +
window.location.host +
window.location.pathname +
'?' + params.join('&');
That code within your change event handler will do the trick.
For instance:
$('#my_dropdown_id').bind('change', function(){
var params = [
"foo=bar",
"base=" + $(this).val()
];
window.location.href = "http://" + window.location.host + window.location.pathname + '?' + params.join('&');
});
If you go with the top rated answer, you may want to replace
http://
in the code with
window.location.protocol
so that it works for other protocols, like https or file. So
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.join('&');
Actually, there a built-in function of location that you can use, the name of the function is assign.
For appending or modifying there is another built-in function of the URL class that you can use too. the name of the function is searchParams.
So for your case you just need below example:
const url = new URL(location.href);
url.searchParams.set('key', 'value');
location.assign(url.search);
Update 2022
I create a TypeScript function to apply redirect with params more easier:
const isClient = (): boolean => typeof window !== 'undefined';
type ParamsType = { [key: string]: string | number };
const redirectUrl = (url: string, params?: ParamsType): void => {
if (isClient()) {
try {
const _url = new URL(url);
if (params) {
const keyList = Object.keys(params);
for (let i = 0; i < keyList.length; i += 1) {
const key = keyList[i];
_url.searchParams.set(keyList[i], params[key]?.toString());
}
}
window.location.assign(_url.href);
} catch (e) {
throw new Error('The URL is not valid');
}
}
};
export default redirectUrl;
If you want a simple way to preserve the query string and possibly append to it, use window.location.search; here's a snippet:
var search = window.location.search + (window.location.search ? "&" : "?");
search += "param1=foo&param2=bar";
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + search;
You can, of course, use a more sophisticated way of building the rest of your query string, as found in the other examples, but the key is to leverage Location.search.
If you have an existing querystring that you'd like to keep then this version does that and adds your new params to any existing ones. The keys are converted to lowercase so that duplicates are not added. Maintaining the quersytring does make the solution more complicated, so I'd only do this if you need to.
$("#sortby").change(function () {
var queryString = getQueryStrings();
// Add new params to the querystring dictionary
queryString["sortby"] = $("#sortby").val();
window.location.href =
window.location.protocol + "//" +
window.location.host +
window.location.pathname +
createQueryString(queryString);
});
// http://stackoverflow.com/questions/2907482
// Gets Querystring from window.location and converts all keys to lowercase
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for (var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0]).toLowerCase()] = decode(key[1]);
}
}
return assoc;
}
function createQueryString(queryDict) {
var queryStringBits = [];
for (var key in queryDict) {
if (queryDict.hasOwnProperty(key)) {
queryStringBits.push(key + "=" + queryDict[key]);
}
}
return queryStringBits.length > 0
? "?" + queryStringBits.join("&")
: "";
}
I was having a requirement to open a particular tab after reloading. So I just needed to append the #tabs-4 to the current url. I know its irrelevant to current post but it could help others who come to this just like I did.
Using the code
window.location = window.location.pathname
+ window.location.search + '#tabs-4';
did'nt work for me but below code did.
location = "#tabs-4";
location.reload(true);

Categories