The code below shows a standard JavaScript pattern for defining a function that takes a number of bytes and converts it into a readable format.
In standard JavaScript, you can call the function as a variable, so that the variable value is whatever the function returns.
//Define function
function bytesToReadable(numberOfBytes) {
var readableSize;
var units;
if (numberOfBytes <= 1000) {
readableSize = numberOfBytes;
units = ' bytes';
} else if (numberOfBytes > 1000 && numberOfBytes <= 1000000) {
readableSize = Math.ceil(numberOfBytes / 1000);
units = ' KB';
} else if (numberOfBytes > 1000000 && numberOfBytes <= 1000000000) {
readableSize = (numberOfBytes / 1000000).toFixed(2);
units = ' MB';
} else if (numberOfBytes > 1000000000 && numberOfBytes <= 1000000000000) {
readableSize = Math.ceil(numberOfBytes / 1000000000);
units = ' GB';
}
var prettySize = readableSize + units;
return prettySize;
}
//Call function
var test = bytesToReadable(2360000);
console.log(test);//Logs '2.36MB'
What is the correct way of achieving this type of pattern in Ember?
I have tried placing the code in it's own action as below, but this returns undefined:
actions: {
bytesToReadable: function(numberOfBytes) {
var readableSize;
var units;
if (numberOfBytes <= 1000) {
readableSize = numberOfBytes;
units = ' bytes';
} else if (numberOfBytes > 1000 && numberOfBytes <= 1000000) {
readableSize = Math.ceil(numberOfBytes / 1000);
units = ' KB';
} else if (numberOfBytes > 1000000 && numberOfBytes <= 1000000000) {
readableSize = (numberOfBytes / 1000000).toFixed(2);
units = ' MB';
} else if (numberOfBytes > 1000000000 && numberOfBytes <= 1000000000000) {
readableSize = Math.ceil(numberOfBytes / 1000000000);
units = ' GB';
}
var prettySize = readableSize + units;
return prettySize;
},
anotherAction: function() {
var test = this.send('bytesToReadable', 2360000);
console.log(test) //Logs undefined.
},
}
bytesToReadable: function(numberOfBytes) {
var readableSize;
var units;
if (numberOfBytes <= 1000) {
readableSize = numberOfBytes;
units = ' bytes';
} else if (numberOfBytes > 1000 && numberOfBytes <= 1000000) {
readableSize = Math.ceil(numberOfBytes / 1000);
units = ' KB';
} else if (numberOfBytes > 1000000 && numberOfBytes <= 1000000000) {
readableSize = (numberOfBytes / 1000000).toFixed(2);
units = ' MB';
} else if (numberOfBytes > 1000000000 && numberOfBytes <= 1000000000000) {
readableSize = Math.ceil(numberOfBytes / 1000000000);
units = ' GB';
}
var prettySize = readableSize + units;
return prettySize;
},
actions: {
anotherAction: function() {
var test = this.get('bytesToReadable', 2360000);
console.log(test);//Logs the function itself.
},
}
I would like to be able to run this code from various different parts of my application. What is the best way to make such a function available throughout my app, so that it can return the result to the function it has been called from?
Aucun commentaire:
Enregistrer un commentaire