I have the following code in my Aurelia app:
import {digit} from "../util/random" // generates a random digit [0,9]
export class UnitedStates {
zipCode() {
return ""+digit(5);
};
zipPlus4() {
return this.zipCode()+"-"+digit(4);
};
...
}
Getting the error TypeError: Cannot read property 'zipCode' of null on the body of zipPlus4. Inspection in the developer tool reveals that this is null.
Why is this null, and how do I fix this?
This is an issue with the transpiler. Recall that the arrow function notation maintains lexical this (or read here for more). So, when Babel and other transpilers enter a new scope, they maintain a local this variable so that it will be accessible from any child scopes. Usually, this variable is _this.
Sometimes, debuggers like DevTools have a hard time understanding the sourcemaps, and they report a null this. Turns out, this is only when inspecting the code; when running the code, it works properly.
So how do you inspect the value of this when it is reported to be null? Inspect _this, usually from the console. That will give you the true this value that is being used.
Related
My recent work in Vue (we're still using Vue 2 unfortunately) has caused me to question my understanding of how Vue checks property values and re-renders.
I've got a couple of components on my page which have a v-show clause tied to a get statement in the code:
<my-component v-show="this.isRequired">
public get isRequired(): boolean {
if(this.model.myBooleanProperty == true && this.model.myNumberProperty > 0) {
return true;
}
if(this.model.myOtherBooleanProperty == true && this.model.myOtherNumberProperty > 0) {
return true;
}
return false;
}
Now, my understanding is that Vue would check this function whenever any of the involved properties changed. So if the values of any out of myBooleanProperty, myNumberProperty, myOtherBooleanProperty and myOtherNumberProperty changed then isRequired would be checked and the v-show clause would cause the component to show or not show depending on the outcome.
However, I've learned this isn't the case. By commenting out parts of the function, it seems that only changes to myBooleanProperty, myNumberProperty, myOtherBooleanProperty ever cause isRequired to be checked, even if they're taken out of the function. myOtherNumberProperty never causes it to be checked, even if it's directly manipulated in isRequired by setting it to zero or null.
Can someone please explain what, under these circumstances, causes Vue to reevaluate the value of isRequired?
Don't use this in the template, it's not necessary.
I understand you use vue-property-decorator library, right? Cause a get x property is a class getter, which is compiled down to a Vue computed property.
You are right, computed properties react and reevaluate whenever one of their reactive dependency updates. myOtherNumberProperty should also trigger the computed to reevaluate its value.
Maybe you have a reactivity problem with this property. Check that this value is properly initialized in your data function. If it's missing in the initial model object, Vue won't make it reactive and thus, its changes won't trigger anything.
I can't help further more without additional context on your code.
As mentioned, I'm using the Marvel API. At mounted() I use this action:
mounted() {
this.$store.dispatch("get/getCharacter", this.$route.params.id);
},
This uses axios to call for the character object, and sends that payload to a mutation, which updates the state of character: {}. I use a getter to call the state of the character to output in my page. Everything works, the image appears and if I interpolate the string to the page, that appears as it should. However, I'm still getting the typeError. I'm creating the img like this:
<img :src="`${character.thumbnail.path}/portrait_incredible.${character.thumbnail.extension}`
So, doing this {{ character.thumbnail.path }} outputs the correct 'path' string from the object. The image loads perfectly on my computer too, but not on my Oppo phone (I've uploaded it to Netlify to check). Strangely, my friends iPhone does load the images using the Netflify link.
What am I doing wrong, and how can I make this error go away?
Thanks for any help!
I know this question is old, but I would like to give my solution since no one has answered this question. So it may help someone in future.
You can use the optional chaining operator to solve this,
The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.
See Optional chaining (?.)
character.thumbnail?.path
character.thumbnail?.extension
I have the following code in Rust, which does not compile, but shows the intent of what I'd like to do.
pub fn parse(cursor: &mut io::Cursor<&[u8]>) -> io::Result<Ack> {
use self::byteorder::{BigEndian, ReadBytesExt};
use self::core::error::Error;
match cursor.read_u16::<BigEndian>() {
Err(byteorder::Error::Io(error)) => Err(error),
Err(error) =>
Err(io::Error::new(io::ErrorKind::Other, error.description(),
None)),
Ok(value) => Ok(Ack { block_number: value })
}
}
Essentially, I want to take the error description of an error returned by the byteorder library and use it to create the description of an error I'll pass back to the user of my library. This fails with packets.rs:166:58: 166:63 error:errordoes not live long enough, and I understand why.
The byteorder library solves this issue by wrapping an std::io::Result in the byteorder::Error::Io constructor. However, I don't want to take this route because I'd have to define my own error type that wraps either an std::io::Error or a byteorder::Error. It seems to me that my users shouldn't know or care that I use the byteorder library, and it shouldn't be part of my interface.
I'm a Rust newbie and don't yet know the idioms and best practices of the language and design. What are my options for dealing with this?
Your problem is in fact in that io::Error::new()'s second parameter is &'static str, while byteorder::Error::description() returns a &'a str where 'a is lifetime of the error object itself which is less than 'static. Hence you can't use it for io::Error's description.
The simplest fix would be moving byteorder::Error description to detail field of io::Error:
Err(error) =>
Err(io::Error::new(
io::ErrorKind::Other,
"byteorder error",
Some(error.description().to_string())
)),
However, you should seriously consider making a custom wrapper error type which encapsulates all "downstream" errors. With properly written FromError instances you should be able to write something like
try!(cursor.read_u16::<BigEndian>()
.map(|value| Ack { block_number: value }))
instead of your whole match. Custom error wrappers will also help you when your program grows and more "downstream" error sources appear - you could just add new enum variants and/or FromError implementations to support these new errors.
I cannot test your code so I can't be sure. Isn't the ref keyword enough?
Err(byteorder::Error::Io(ref error)) => Err(error),
I'm getting the following error when trying to execute my custom build definition (containing only 1 custom CodeActivity):
Exception Message: Expression Activity type 'CSharpReference`1' requires compilation in order to run. Please ensure that the workflow has been compiled. (type NotSupportedException)
I've tried multiple suggested answers to this error, but none of them are applicable to my activity. My CodeActivity only has a couple of methods that search through directories for specific files, and then returns a delimited string containing the file names.
I don't use any WorkflowInvoker or any DynamicActivities. For what reason would I keep getting this error?
Thanks
I had the same error on an assignment step.
System.NotSupportedException: Expression Activity type 'CSharpValue`1' requires compilation in order to run.
Please ensure that the workflow has been compiled.
The resolution was to remove the carriage returns from statement.
For example this works:
new Foo() { Bar = new Bar() { MyProp1 = "123" } }
This does not:
new Foo()
{
Bar = new Bar()
{
MyProp1 = "123"
}
}
I decided not to work in a clean xaml file, but instead to use the Default Template provided by TFS. The Default template ran my activities without errors.
I was able to fix this solution as well by using the Default Template provided by TFS, clearing all of their activities, and adding the custom activities and arguments in my original custom template.
However, more insight in to this issue, it seems to be caused by the fact that custom template use C# expressions to handle the arguments. Where as the default template is set up to use VB Expressions for it's arguments.
In my case, the language didn't matter because the values were simply strings.
I'm using this with BundleTransformer from nuget and System.Web.Optimisation in an ASP.Net app. According to various docs this minifier is supposed to "remove unreachable code". I know it's not as aggressive as google closure (which I can't use presently) but I can't get even the simplest cases to work, eg;
function foo() {
}
where foo isn't called from anywhere. I can appreciate the argument that says this might be an exported function but I can't see a way to differentiate that. All my JS code is concatenated so it would be able to say for sure whether that function was needed or not if I can find the right switches.
The only way I've found to omit unnecessary code is to use the debugLookupList property in the web.config for BundleTransformer but that seems like a sledgehammer to crack a nut. It's not very granular.
Does anyone have an example of how to write so-called 'unreachable code' that this minifier will recognise?
Here's a place to test online
I doubt the minifier has any way of knowing if a globally defined function can be removed safely (as it doesn't know the full scope). On the other hand it might not remove any unused functions and might only be interested in unreachable code (i.e. code after a return).
Using the JavaScript Module Pattern, your unused private functions would most likely get hoovered up correctly (although I've not tested this). In the example below, the minifier should only be confident about removing the function called privateFunction. Whether it considers unused functions as unreachable code is another matter.
var AmazingModule = (function() {
var module = {};
function privateFunction() {
// ..
}
module.otherFunction = function() {
// ..
};
return module;
}());
function anotherFunction() {
// ..
}