I'm learning VueJS. I'm figuring out their currency validation example code.
Vue.component('currency-input', {
template: `
<span>
$
<input
ref="input"
v-bind:value="value"
v-on:input="updateValue($event.target.value)">
</span>
`,
props: ['value'],
methods: {
// Instead of updating the value directly, this
// method is used to format and place constraints
// on the input's value
updateValue: function (value) {
var formattedValue = value
// Remove whitespace on either side
.trim()
// Shorten to 2 decimal places
.slice(
0,
value.indexOf('.') === -1
? value.length
: value.indexOf('.') + 3
)
// If the value was not already normalized,
// manually override it to conform
if (formattedValue !== value) {
this.$refs.input.value = formattedValue
}
// Emit the number value through the input event
this.$emit('input', Number(formattedValue))
}
}
})
The $emit call at the bottom of the updateValue function, triggers an input event.
When I comment it out, the real time currency validation no longer works. So I realize it has a purpose.
But why trigger an input event inside an input event?
You'd think the input event would fire again, causing the updateValue handler to fire again, causing a stack overflow due to recursive calls.
I understand VueJS's much simpler $emit example code. It's just like Jquery's trigger function.
vm.$on('test', function (msg) {
console.log(msg)
})
vm.$emit('test', 'hi')
// -> "hi"
But in the currency validation example, I do not understand why $emit is used the way it's used, and why it works the way it works.
Can somebody explain?
The Emit call here is to allow you to hook into the event in parent contexts. The Input event is also used by the v-model directive to handle two way binding with components.
v-model='model' is essentially v-bind:value='model' v-on:input='model = $event.target.value' with some added bits to make it play nice. When you remove the this.$emit('input', Number(formattedValue)) You're removing the mechanism that updates the value outside the component.
EDIT: #Jay careful what you wish for sometimes
All elements in HTML have a series of native handlers for the common events; resize, load, unload, etc. These handle what to do when the page changes it's rendering and can be disabled or added onto, since the introduction of JavaScript browsers have used an event pump system that allows multiple functions to be attached to any event which run in sequence when the event is raised. An example being how you can have 3 functions run on resize to handle edge cases such as minimum/maximum size, screen orientation etc.
Form elements generally implement their own base event functions: keydown, keyup, mousedown, mouseup. These base functions invoke events to make our lives easier as developers, these being: input, blur, focus. Some have specialized events as in select elements implementing change, form tags implementing submit.
Input tags on focus capture keyboard input and display the text input cursor to indicate that it's ready to receive input. It adds in handlers for the tab keycode which finds the next available input and shifts focus to that element. The event pump style function system is great here as it allows you to bind to focus and do things like change the background color or border when the input is focused without having to implement the code for capturing input or displaying the cursor yourself.
Input tags also raise the input event when you type in them indicating that the input has changed, telling the browser to change the value and update the display so that the functionality expected by the user is consistent.
In the currency-input example we are adding the updateValue function to work with the native function and process the input value of the event, in the updateValue function we modify the string representation of the value and need someplace to put it. You could simply add a data property to hold the value and bind the input's value property to the data property allowing the currency-input to internally handle the display of the result but that would lock the value behind a private accessor and you would be unable to modify or retrieve the value of the resulting currency formatted value.
Using this.$emit('input', Number(formattedValue)) the updateValue function is acting similar to the native input tag by raising an event that can be captured by the parent context and worked with. You can store it in a value, use it as the basis for a function, or even ignore it completely though that may not help much. This allows you to keep track of the value of the input and modify it as needed or send it to the server, display it, etc.
It also ties into a few directives most pertinently v-model which is syntactic sugar to allow for a value property binding and an input event binding to a data property inside the current context. By providing a value prop and emitting an input event a custom element can act similar to a native form element in the systems of a Vue application. An extremely attractive feature when you want to package and distribute or reuse components.
It's a lot nicer to go:
...
<currency-input v-model='dollarValue'></currency-input>
<input v-model='dollarValue'>
...
Than to have to add in value and input bindings everywhere ergo:
...
<currency-input v-bind:value='dollarValue' v-on:input='updateDollarValue($event.target.value)'></currency-input>
<input v-bind:value='dollarValue' v-on:input='updateDollarValue($event.target.value)'>
...
Now that my weird rambling is done, I hope this helped with understanding some of the patterns and reasoning behind the currency-input example.
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.
After testing out a few other engines I've settled into Godot for my game development learning process and have really appreciated the conciseness of GDScript, the node/inheritance structure, and the way observer events are covered by signals. I've been building knowledge through various tutorials and by reading through the documentation.
Somehow I'm struggling to solve the very fundamental task of detecting a mouseclick on a sprite. (Well, on a sprite's parent node, either a Node2D or an Area2D.)
My process has been this:
Create an Area2D node (called logo) with a Sprite child and a CollisionShape2D child
Assign a texture to the Sprite node, and change the x and y extent values of the CollisionShape2D node to match the size of the Sprite's texture
Connect the _on_logo_input_event(viewport, event, shape_idx) signal to the Area2D node's script (called logo.gd)
Use the following code:
func _on_logo_input_event(viewport, event, shape_idx):
if (event is InputEventMouseButton && event.pressed):
print("Logo clicked")
When I run the game I get nothing in the output after clicking, and see these errors:
The argument 'viewport' is never used in the function '_on_logo_input_event'. If this is intended, prefix it with an underscore: '_viewport'
The argument 'shape_idx' is never used in the function '_on_logo_input_event'. If this is intended, prefix it with an underscore: '_shape_idx'
I don't know how to address the parameters in this signal's function - My Area2D node is set to Pickable, and the logo Area2D node is a direct child to the game_window Node2D in the main scene. I can't figure out what is going wrong here, whether it's some project setting I need to change or an inspector attribute I need to set. Is there a better way to feed an input signal for a mouse click into a script?
I don't want to clutter stackoverflow with such a simple question but I've tried to do my due diligence and haven't been able to find this error message on any forums. I'd appreciate any help, thanks.
If the CollisionLayer of your Area2D is not empty, and input_pickable is on, then it is capable to get input. Either by connecting the input_event signal or by overriding _input_event.
If that is not working, the likely cause is that there is some Control/UI element that is stopping mouse events. They have a property called mouse_filter, which is set to Stop by default. You will need to find which Control is intercepting the input, and set its mouse_filter to Ignore.
By the way, these:
The argument 'viewport' is never used in the function '_on_logo_input_event'. If this is intended, prefix it with an underscore: '_viewport'
The argument 'shape_idx' is never used in the function '_on_logo_input_event'. If this is intended, prefix it with an underscore: '_shape_idx'
These are warnings. They are not the source of the problem. They tell what they say on the tin: you have some parameter that you are not using, and you can prefix its name with an underscore as a way to suppress the warning.
I would also recommend checking out this video:
https://www.youtube.com/watch?v=iSpWZzL2i1o
The main modification that he makes from what you have done is make a separate click event in Project > Project Settings > Input Map that maps to a left click. He can then reference that in the _on_Area2D_input_event.
extends Node2D
var selected = false
func _ready():
pass
func _on_Area2D_input_event(viewport, event, shape_idx):
if Input.is_action_just_pressed("click"):
selected = true
func _physics_process(delta):
if selected:
global_position = lerp(global_position, get_global_mouse_position(), 25 * delta)
func _input(event):
if event is InputEventMouseButton:
if event.button_index == BUTTON_LEFT and not event.pressed:
selected = false
Why this "value" can not be written as "pricevalue" or other, otherwise input will not convert non-numeric values
In the props element, you are defining the properties your component will attach to. You can call them whatever you want. You need to be clear about a couple of things...
You define the name here in camelCase, but when you call the component in the parent markup, use kebab-case.
methods only run when they are called. If you put your formatting on the downstream side (receiving a value and displaying it), everything will be reactive and all your values should display correctly. It will all just work whenever the source value changes. So do your formatting in a computed, like this...
js
computed: {
formattedPriceValue(){
return Number.parseFloat(this.priceValue).toFixed(2)
}
}
You can also just do it inline...
markup
<input type="number" :value="Number.parseFloat(priceValue).toFixed(2)">
The value you want to emit is probably the unformatted output of Number.parseFloat #change="$emit('price-changed', Number.parseFloat(event.target.value))"
Then, you will live longer if you do your number formatting with the Number functions provided.
Also, why don't you use the new template (multi-line) strings, delimited by a backtick `. They're much cleaner than the line continuation character you're using.
ps. I love seeing the chinese (?) comments in the code. I've copied and pasted them into my code. I hope there's no swearing. Unicode rocks.
Is it possible to access arguments/parameters passed to an emitted event within an inline / in-template handler? Something like:
<component #some-event="someObject.field = $arguments[0]"></component
What I'm trying to do exactly is assign a value to an object in the scope. I know I can create a method to do that and use it as a handler for the event but I was wondering if this could work as an inline statement.
It is not $arguments[0], but just arguments[0] (without the $). I am surprised that it actually works in the inline handler. So the following code is valid and will work:
<component #some-event="someObject.field = arguments[0]"></component>
The docs for Methods in Inline Handlers specifies $event as a special variable that gets the first parameter passed via event. I have always used it till now.
After reading your question, a bit more research led me to this reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
It seems every javascript function has a local variable called arguments, which is used when a function is expected to get variable number of arguments.
Using arguments[] as inline statements is definitely possible, but not documented anywhere in the context of vue.js framework. On the other hand, if you use $event in inline handler for events, it feels safer as it is documented clearly and will not break in a future version of Vue.js
Sample usage for $event:
<component #some-event="someObject.field = $event"></component>
There is something that not many people know.
Inline handler besides the $event has access to arguments.
For example I was using v-dropzone which is passing many arguments (e.g. file, response).
By using
<v-dropzone #some-event="callMethod($event, 'some other arg')" >
will catch only the first argument.
So the solution was:
<v-dropzone #some-event="callMethod(arguments, 'some other arg')" >
I want to understand in which case I should or have to use the evaluate function.
I have read the API doc about the evaluate function of CasperJS, but I'm unsure in which case I should use this function. And what does DOM context mean? Can somebody provide an example?
The CasperJS documentation has a pretty good description of what casper.evaluate() does.
To recap: You pass a function that will be executed in the DOM context (you can also call it the page context). You can pass some primitives as arguments to this function and return one primitive back. Keep in mind that this function that you pass to evaluate must be self contained. It cannot use variables or functions that are defined outside of this function.
CasperJS provides many good functions for everyday tasks, but you may run into a situation when you need a custom function to do something. evaluate is basically there to do
Retrieve some value from the page to take action based on it in your script
Manipulate the page in some way other than clicking or filling out a form
Combinations of points 1. and 2.
Examples
You may need a generic function to get the checked property from a checkbox. CasperJS currently only provides getElementAttribute function which will not work in this case.
function getChecked(cssSelector){
return document.querySelector(cssSelector).checked;
}
if (casper.evaluate(getChecked, selector)){
// do something
} else {
// do something else
}
In most of the cases it is just preference of what you want to use. If you have a list of users with data-uid on each li element then you have at least 2 possibilities to retrieve the uids.
Casper-only:
var uids = casper.getElementsAttribute('ul#user-list > li', 'data-uid');
Casper-Evaluate:
var uids = casper.evaluate(function(){
return Array.prototype.map.call(document.querySelectorAll('ul#user-list > li'), function(li){ return li["data-uid"]});
});
Regarding manipulation everything is possible but depends on what you want to do. Let's say you want to take screenshots of web pages, but there are some elements that you don't want to be there. Or you could add your own CSS to the document.
Remove elements:
function removeSelector(cssSelector){
var elements = document.querySelectorAll(cssSelector);
Array.prototype.forEach.call(elements, function(el){
el.parent.removeChild(el);
});
}
casper.evaluate(removeSelector, '.ad'); // if it would be that easy :)
Change site appearance through CSS:
function applyCSS(yourCss){
var style = document.createElement("style");
style.innerHTML = yourCss;
document.head.appendChild(style);
}
casper.evaluate(applyCSS, 'body { background-color: black; }'); // non-sense
Roots
CasperJS is built on top of PhantomJS and as such inherits some of its quirks. The PhantomJS documentation for page.evaluate() says this:
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.
Closures, functions, DOM nodes, etc. will not work!