I'm trying to create a logger that outputs a message and the class it's called from, like this:
const __log = (...values: Array<any>) =>
console.log("%c" + this.constructor["name"], CLASS_STYLE, ...values);
This work nicely, but I'd like to keep it DRY, to import it once if possible and call wherever I need to. I was thinking about adding it as window.__log, but of course there's an issue with the scope of this.
What would be the best way to change the scope?
I'm looking for some kind of bind(), call(), apply() trickery/wizardry that would make this work (;
Example planker is here: http://plnkr.co/edit/sLdAsbv8FgO4V1qfqQZM (with Angular2 component). Removing the // const __log ... comment in class App would show what I want to get.
You can archive what you want by doing so:
function __log(...values: Array<any>)
{
console.log("%c" + arguments.callee.caller.name, CLASS_STYLE, ...values)
}
If you want to go deeper, here is some more info about getting full call stack: link
Related
Good Morning, I explain my scenario:
After generating a couple of http calls and after processing them I have a result similar to this:
xxx.component.ts
nameVariable: any = {};
this.nameVariable = this.createMyObject(params);
console.log(this.nameVariable);
Thanks to the console.log() we can see that is an Object: nameVariable like this:
Object: {
information1: Object {...},
information2: Array [...],
information3: Object{...},
information4: Array[...]
}
How can I save this Object??,
how do I Save it and then be able to use it within the code and/or use it within a Component??
Should use a Model?? what should I study to better understand this thing??
Your angular component is a class. The scope of your nameVariable variable is the body of the method where it is defined. You can extend the scope of that variable by introducing it as a field of your class before the constructor of the class as follows:
nameVariable: { (state here the type of the object };
and you may add a prefix like private or public just before the nameVariable word.
Refer to it as this.nameVariable afterwards inside the methods (the const keyword is no more required).
I was working on adding default scopes with function under the Sequelize ORM. I followed the tutorials here http://docs.sequelizejs.com/manual/scopes.html while for Scope takes arguments, we need to pass on object like this
Project.scope('random', { method: ['accessLevel', 19]}).findAll();
So inside my video model code, I add a scope called 'defaultScope'
Video.addScope(
'defaultScope',
(userId) => {
*********** scope description here*********
})
And this is how I use my model:
const videos = await models.video.scope({
method: ['defaultScope', 'I hardcode userId here']
}).findAll();
console.log(videos);`
But I always got an error (node:43214) UnhandledPromiseRejectionWarning: SequelizeScopeError: Invalid scope null called.
If I use another scope name instead of 'defaultScope', my code works and I successfully got the objects back. However since it's a broad level scope I want to make it default. I just feel so confused why the normal scope works but default one not. Can somebody with relevant experience help me figure this out? Thanks!
I'm working on an AngularJS project where there is a .constant() provider to declare some basic information used across the whole project. For example, a definition of cookie name. Ex.:
.constant('appConst', {
cookie: 'CookieName',
...
});
But the same thing can be done by declaring a const, ex.:
const appConst = {
cookie: 'CookieName',
...
}
So, what is the advatage of using the .constant provider instead of just declaring a const? I know one of the reasons is because we don't expect the value to change. But isn't this the same objective of a const?
The new const keyword only makes it so you cannot reassign the variable, it doesn't make any object you initially assign to it immutable. So in your example with:
const appConst = {
cookie: 'CookieName',
...
}
You would still be able to change the value of cookie. You just wouldn't be allowed to do something like this:
appConst = { // My new object };
The values in the angular .constant() can also still be changed, so they're not constant in the common use of the word "constant". At least not when you use it like this:
.constant('appConst', {
cookie: 'CookieName',
...
});
So if you for instance do like this and change the value within a controller
app.controller('myController', function(appConst){
appConst.cookie = 'NewCookieName';
})
the change would be reflected anywhere you inject appConst after this controller was constructed.
You can't "reassign" appConst in this case though, that action would just be ignored, so it is constant in that sense.
1- const is new in ES6, so you may need to transpiler your code for supporting old browsers.
2- const is block-scoped, so within a scenario, you define a constant in A.js, will be not able to use it at B.js unless you're using a module bundler, so we went back to the topic 1-.
The main purpose of AngularJS having this native is to able you to share it between controllers, services, and directives, using its dependency injection system.
Now, I know this is an off-the-wall question and that there is probably not going to be any API level access for doing this. I also understand that doing this is completely unnecessary. However, the implementation that I am aiming for requires for me to be able to make {{ variable }} look inside of the $scope.object instead of the $scope itself.
For example:
Controller($scope) {
$scope.active = ...;
}
In this case you can get the active object through {{active}} and any child elements through {{active.broken}} however for the sake of humoring me, lets assume that all of the variables I'm ever going to have to obtain is going to be part of that active object. So I'll be typing things like.. (Data not related)
{{active.title}}
{{active.author}}
{{active.content}}
You could just say "Well why not just move the title/author/content into the $scope and keep it outside of the active object, as that would achieve the desired result of this:
{{title}}
{{author}}
{{content}}
Well, that's where the problem comes in. This is a controller that is not exposed to my end-user, however the end-user does have a completely mutable object (in this example: active) that they can modify. This object has many [optional] listeners and callbacks that are invoked by the application controller when necessary.
The user's that have used my application during testing have commented on what a drag it is to have to type in active. before everything in order to get the data they wanted. Considering data from the $scope is never rendered to the screen, and only data from active is, I was wondering if perhaps there was a way to change where AngularJS looks when parsing/binding data.
If the goal is to evaluate expressions in a different context than $scope, that can be done with the $parse service.
app.controller("myVm", function($scope, $parse) {
var vm = $scope;
vm.active = { a: 5,
b: 3
};
var.myFn = $parse("a+b");
vm.total = myFn(vm.active);
console.log(vm.total);
});
The above example shows how to evaluate the expression a+b using the properties of the $scope.active object.
The DEMO on JSFiddle
I want to store a private variable on each DS.Model. Its purpose is to store a pending callback (in case I want to cancel it).
I have tried this (and it works):
DS.Model.reopen({
init() {
let _pending; // my private var
this._getPending = () => _pending; // get private var
this._setPending = callback => _pending = callback; // set private var
this._super(...arguments);
}
});
I have placed this in an initializer, and it works as I expect it to.
My questions are: Is this a good practise? is it likely to mess anything up? ...and, is there a better way?
Personally, I'm happy with the way it works.. but I'm not sure if its the "Ember" way. This is going to go into an Ember-cli addon, so I would like it to be the most "best practise" as possible. (the _getPending/_setPending method are only to be used internally within the addon.)
Here are my 2 cents on this. I would say no it is not a good practice, but it should be okay since they are just Ember Objects. The question here is what is Ember data model used for? From doc it says:
"Models are objects that represent the underlying data that your application presents to the user."
By definition this is not what they are designed for, so just because you are able to it does not mean that you should use them like this.
Pending callback so it can be canceled? Ember model API has defined state objects that can be used for this purpose. http://emberjs.com/api/data/classes/DS.Model.html Flags like isDeleted, isValid, isNew...gives all possible state.
I would place them in router actions where they are easy tested with integration tests.
You can check this screencast that explains them:
https://www.emberscreencasts.com/posts/102-ember-data-20-model-states-and-flags
Hope it helps.