How to retrieve the stored value from goinstant - goinstant

I'm doing something wrong. I'm attempting to get the stored value I have in goinstant. I have a person room with a userName. The value the alert function displays is "[object Object]". Here is my code: (I left out the scripts intentionally). I provided a quick screen shot of my person data on goInstant for reference http://screencast.com/t/BtLqfrorg
<h2>Angular JS Test</h2>
<div ng-app="testapp" data-ng-controller="personCtrl">
<input type="text" ng-model="userName" />{{ userName }}
<button type="submit" id="save" name="save" >Save</button>
<script>
var testApp = angular.module('testapp', ['goangular']);
testApp.config(function($goConnectionProvider) {
$goConnectionProvider.$set('https://goinstant.net/<mykey>/test');
});
testApp.controller('personCtrl', function($scope, $goKey) {
// $goKey is available
$scope.userName = $goKey('/person/userName').$sync();
alert($scope.userName);
});
</script>
</div>

Your example would indicate that you expect $scope.userName to be a primitive value (a string). It is in fact, a model. Models provide a simple interface for updating the state of your application, and in GoAngular, that state is persisted to your GoInstant App auto-magically.
You can find more documentation on the GoAngular Model here. I thought a working example might help, so I've created a Plunker. Let's work through the script.js:
angular
.module('TestThings', ['goangular'])
.config(function($goConnectionProvider) {
$goConnectionProvider.$set('https://goinstant.net/mattcreager/DingDong');
})
.controller('TestCtrl', function($scope, $goKey) {
// Create a person model
$scope.person = $goKey('person').$sync();
// Observe the model for changes
$scope.$watchCollection('person', function(a, b) {
console.log('model is', a.$omit()); // Log current state of person
console.log('model was', b.$omit()); // Log the previous state of person
});
// After 2000 ms set the userName property of the person model
setTimeout(function() {
$scope.person.$key('userName').$set('Luke Skywalker');
}, 2000);
// Set the userName property of the person model
$scope.person.$key('userName').$set('Darth Vader');
});

Related

What is the best way to post form with multiple components using Vue js

as I'm on my Vue spree (started recently but so far I'm really enjoying learning this framework) couple of questions rised up. One of which is how to post form from multiple components. So before I continue forward I wanted to ask you what are you thinking about this way of structuring and point me in right direction if I'm wrong.
Here it goes.
I'm working on a SPA project using ASP.NET CORE 2.1 and Vue JS Template (with webpack)(https://github.com/MarkPieszak/aspnetcore-Vue-starter) and my project is structured in several containers, something like this:
In my app-root i registered several containers
<template>
<div id="app" class="container">
<app-first-container></app-first-container>
<app-second-container></app-second-container>
<!--<app-third-container></app-third-container>-->
<app-calculate-container></app-calculate-container>
<app-result-container></app-result-container>
</div>
</template>
<script>
// imported templates
import firstContainer from './first-container'
import secondContainer from './second-container'
import calculateContainer from './calculateButton-container'
//import thirdContainer from './third-container'
import resultContainer from './result-container'
export default {
components: {
'app-first-container': firstContainer,
'app-second-container': secondContainer,
// 'app-third-container': thirdContainer,
'app-calculate-container': calculateContainer,
'app-result-container': resultContainer
}
}
</script>
In my first container I'm having several dropdowns and two input fields with my script file where I'm fetching data from API and filling dropdowns and input fields with fetched data.
Something like this ( entered some dummy code for demonstration)
<template>
<div>
<h1>Crops table</h1>
<p>This component demonstrates fetching data from the server. {{dataMessage}}</p>
<div class="form-row">
<div class="form-group col-md-6">
<label for="exampleFormControlSelect1" class="col-form-label-sm font-weight-bold">1. Some text</label>
<select class="form-control" id="exampleFormControlSelect1" v-model="pickedCropType" #change="getCropsByType()">
<option v-for="(cropType, index) in cropTypes" :key="index" :value="cropType.id" :data-imagesrc="cropType.imgPath">{{ cropType.name }}</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="exampleFormControlSelect2" class="col-form-label-sm font-weight-bold">2. Some text</label>
<select class="form-control" id="exampleFormControlSelect2">
<option v-for="(crop, index) in cropSelectList" :key="index" :value="crop.id">{{ crop.name }}</option>
</select>
</div>
</div>
</div>
</template>
<script>
import { mapActions, mapState } from 'vuex'
export default {
data() {
return {
cropTypes: null,
cropSelectList: null,
crops: null,
pickedCropType: null,
}
},
methods: {
loadPage: async function () {
try {
//Get crop types and create a new array with crop types with an added imgPath property
var cropTypesFinal = [];
let responseCropTypes = await this.$http.get(`http://localhost:8006/api/someData`);
responseCropTypes.data.data.forEach(function (element) {
cropTypesFinal.push(tmpType);
});
} catch (err) {
window.alert(err)
console.log(err)
}
},
getCropsByType: async function () {
//Get crops by crop type
let responseCrops = await this.$http.get(`http://localhost:8006/api/crop/Type/${this.pickedCropType}`);
var responseCropsData = responseCrops.data.data;
this.cropSelectList = responseCropsData;
}
},
async created() {
this.loadPage()
}
}
</script>
And in my second container I have different dropdowns and different input fields with different scripts etc.
So, my questions are:
1.) I'm having required data form field in first container and in second container I'm having additional data and my submit button is separated in third container (app-result-container). So, is this proper and logical way of structuring containers if not can you point me in right direction?
2.) Is it smart to input script tag in every container where I'm processing/fetching/submitting some data for that particular container? Should I put scripts tag in separated file and keep structure clean, separating html from js file.
Example:
import { something } from 'something'
export default {
data () {
return {
someData: 'Hello'
}
},
methods: {
consoleLogData: function (event) {
Console.log(this.someData)
}
}
}
3.) Can I send input values from one container to another (In my particular case from first and second container to app-calculate-container(third container))?
How to on submit return results container with calculated imported values
If you want components to communicate or share data with one another, you will need to either emit an event from one component up to the parent and pass it down via props, or use some kind of state management model, like Vuex, where each of your components can listen to the store.
Take a look at this code sandbox: https://codesandbox.io/s/8144oy7xy2
App.vue
<template>
<div id="app">
<child-input #input="updateName" />
<child-output :value="name" />
</div>
</template>
<script>
import ChildInput from "#/components/ChildInput.vue";
import ChildOutput from "#/components/ChildOutput.vue";
export default {
name: "App",
components: {
ChildInput,
ChildOutput
},
data() {
return {
name: ""
};
},
methods: {
updateName(e) {
this.name = e.target.value;
}
}
};
</script>
ChildInput.vue
<template>
<input type="text" #input="changeHandler">
</template>
<script>
export default {
name: "ChildInput",
methods: {
changeHandler(e) {
this.$emit("input", e);
}
}
};
</script>
ChildOutput.vue
<template>
<p>{{ value }}</p>
</template>
<script>
export default {
name: "ChildOutput",
props: {
value: {
type: String,
default: ""
}
}
};
</script>
What's going on?
The ChildInput component is a text field and on every change inside it, fires an event (emits using this.$emit() and passes the whole event up).
When this fires, App is listening to the change, which fires a method that updates the name data property.
Because name is a reactive data property and is being passed down as a prop to the ChildOutput component, the screen re-renders and is updated with the text written.
Neither ChildInput nor ChildOutput knows about one another. It's the parent that listens to the event passed to it, then passes the new prop down.
This way of working is fine and simple to understand, but I would strongly recommend looking at Vuex, as this method can get messy and complicated when you go beyond trivial tasks.

Clearing form input in Meteor

I have tried multiple options that I have found on SO and elsewhere for clearing form inputs, all listed below in the code, but nothing seems to work. Is there anything specific about this form that would determine which one I should use?
<template name="CompanyAdd">
<div>
<form class="form-inline">
<div class="form-group">
{{> inputAutocomplete settings=companySettings id="companyAdd" name="companyAdd" class="input-xlarge" autocomplete="off" placeholder="Add Company"}}
</div>
<button type="submit" class="btn btn-default company-add">Add</button>
</form>
</div>
</template
Template.CompanyAdd.events({
'submit form': function(e) {
e.preventDefault();
var selection = $(e.target).find('[id=companyAdd]').val();
var company = {
ticker: selection
};
if(Companies.findOne({ticker:selection})) {
console.log("Do nothing");
} else {
Meteor.call('companyAdd', company, function(error, result) {
});
}
//event.target.reset();
//e.target.reset();
//target.text.value = '';
//template.find("form").reset();
//document.getElementById("companyAdd").reset();
}
});
Given that you have
var selection = $(e.target).find('[id=companyAdd]').val();
That is the input you want to clear and that - I assume - works, I would do:
var field = $(e.target).find('[id=companyAdd]');
var selection = field.val();
...
field.val('')
Otherwise if you wish to reset all form, go for #JeremyK`s #reset.
Your second attempt:
e.target.reset();
should work fine. If it is not working, check if there are any errors in the console and report back here.
The handler function receives two arguments: event, an object with
information about the event, and template, a template instance for the
template where the handler is defined.
In your code above you define your handler like this:
'submit form': function(e) {
You have named the event argument e, and discarded the template argument.
e is has information about the event
e.target is the form element (The event was defined on 'submit form')
e.target.reset succeeds because reset is a valid function to call on a form.
Briefly, your other attempts failed because:
event.target.reset(); event is not defined or passed in, at least not with the name event (you used e)
target.text.value = ''; target is an undefined variable
template.find("form").reset(); this fails because template is undefined. If you change your handler definition to receive the template variable, this will work (change 'submit form': function(e) to 'submit form': function(e, template)
document.getElementById("companyAdd").reset(); This fails because the element with the id companyAdd is the input element, not the form, so .reset() is undefined. You could change this to document.getElementById("companyAdd").text.value = ''

In Reactjs how do I update the correct value in the parent state with a callback that's been passed to a nested child component?

I've been on this one for days, and all my reading hasn't helped me find a clean solution for this particular case.
Issue
I can send a parent state value and callback down to a nested component, but once the callback is triggered in the child I don't know how I can send the updated value back to the parent so it can update the correct value.
For instance
Parent Component (Has values and the callback)
Child Component (Values and callback is passed here)
Grand Child Component (Values Updated here and callback triggered)
What is SEEMS to cause the Issue
It seems the issue is I need the original key name in order for "setState" to update the correct value in the parent component(or at least it seems that way), but the child component only has original value and new updated value and has no access to the key associated with original value in the parent component.
Important Notes on Best Practice Surrounding this question
-From what I understand it is bad practice to use refs to handle nested situations like this.
-It seems like there is a cleaner solution than sending a prop for the key and another for the value.
-I'm assuming also that flux might provide a solution to this issue but I feel that there is a basic component to component communication technique or principle that I'm missing here.
Here is a bare bones example of what I'm dealing with.
/*All the values need to be updated here so that the inputs can used for calculation and then sent to a component that displays the output*/
var Calculator =
React.createClass({
getInitialState:function(){
return {
value1: "Enter value 1", /*These values are passed to a nested child component, can't figure how to update the right one*/
value2: "Enter value 2",
}
},
update: function(update){
this.setState(
update
);
},
render: function () {
return (
<div>
<h2>Input</h2>
<Input onClick={this.handleClick} update={this.update} value1={this.state.value1} value2={this.state.value2} /> //pass the values here
<h2>Output</h2>
<Output />
</div>
);
},
handleClick: function () {
//want to update the state for the correct value here
}
});
/* A compenent that is a middle layer between the parent and nested child component I'm working with*/
var Input =
React.createClass({
update: function(){
this.props.update();
},
render:function(){
return (
<div>
<p><InputComponent update={this.update} value={this.props.value1} /> / <InputComponent value={this.props.value2}/></p>//passing down values again
<p><ButtonComponent onClick={this.props.onClick} /></p>
</div>
)
}
});
/*This is the child component that gets the value and call back from the top level component. It will get updates to the values and send them back to change state of the parent component.*/
var InputComponent =
React.createClass({
handleChange: function(event) {
this.props.update();
},
render: function() {
return <input type="text" value={this.props.value} onChange={this.handleChange} />; //this props value has no key associated with it. Cant't make update object ie {originalkey:newValue}
}
});
/* This component is triggered to carry out calculations in the parent class.*/
var ButtonComponent =
React.createClass({
render:function(){
return <button onClick={this.handleClick}> {this.props.txt} </button>
},
handleClick: function(){
this.props.onClick();
}
});
/*The inputs will be calculated and turned to outputs that will displayed here.This component doesn't matter for the question so I left it empty*/
var Output =
React.createClass({
});
Here's an example I just put together on jsfiddle.
Instead of putting update in setState, we pass a value to update from the child component and let the parent set its state.
In the parent, we have:
_update: function(val){
this.setState({
msg: val
});
},
render: function() {
return (
<div>
<p>Message: {this.state.msg}</p>
<Child _update={this._update} />
</div>
);
}
And in the child, we have a _handleClick function that calls the parent _update function with values:
_handleClick: function(){
this.props._update(React.findDOMNode(this.refs.text).value);
},
render: function(){
return (
<div>
<input type="text" ref="text" />
<button onClick={this._handleClick}>Update</button>
</div>
);
}

React with server side variables

I'm rendering out components that have properties with liquid strings. These components are being rendered on the server and picked back up again in the client. Essentially I'm using the DOM as a data store. I'm debating on methods of where to store the data. I need the component to render out valid markup to the server for SEO. But I don't need to pick back up the variable like I am here with this.refs.variantId.getDOMNode(). I could for instance set the variantId to a global client side javascript variable somewhere higher then this code in essence something like var variantId = "{{ product.variants[0].id }}";.
This component will render to a string and be placed within a template file on a server, the server will process that HTML come across the {{ product.variants[0].id }} variable and turn it into something like 1058477584. My component needs to reach into the existing DOM for itself and pull the value out.
var React = require("react");
var $ = require("jquery");
module.exports = React.createClass({
handleSubmit: function(e){
e.preventDefault();
var variantId = this.refs.variantId.getDOMNode().value.trim();
$.ajax({
url: "/cart/add.js",
method: "post",
dataType: "json",
data: {
"id": variantId,
"quantity": this.props.quantity,
},
success: function(data) {
// emit cart added event
}.bind(this),
error: function(xhr, status, err) {
// emit error event (cart added)
}.bind(this)
});
},
getDefaultProps: function(){
return {
quantity: 1,
variantId: "{{ product.variants[0].id }}",
buttonText: "Add to cart"
}
},
render: function() {
return (
<div className="buyButton">
<form action="/cart/add" method="post" encType="multipart/form-data" onSubmit={this.handleSubmit}>
<input type="hidden" name="quantity" value={ this.props.quantity } />
<input type="hidden" name="id" ref="variantId" value={ this.props.variantId } />
<button type="submit" className="btn btn-holstee">{this.props.buttonText}</button>
</form>
</div>
);
}
});
I'm wondering what people think about rendering components with another templating language as a string property. Does it make sense to store that data anywhere else? I don't have access to a server that can store individual pages. It's all templates so multiple data sources need to be handled by one route.
Is there a better way to abstract the liquid out of the component?
Is there a better way to call DOMNodes / update all the props to DOMNodes?
I do something similar in my app. I serialize with JSON and put it in a script tag in the DOM
<script type="application/json" id="preload-notifications">{{json_encode($preload_notifications)}}</script>
Then,
var raw = document.getElementById('preload-messaging');
if (raw === null) {
return ;
}
var data = JSON.parse(raw.text);
I use the flux architecture so it's really simple
this.dispatch('messaging', {
messages: data
});
But you could can inject it as a prop.
React.render(<MessagingContainer messages={data} />, messageDomNode);
Whatever you do, I suggest you don't query the DOM inside a React component. Try to pass stuff as props as much as possible.

Mvvm with knockout : array binding and changing inner objects state

I have an array in my View Model. Items of this array are objects of Person that has two properties. when I bind this to a template it's okay. but when I change the state of one of the properties it does not reflect in UI.
what did I do wrong ?
<script type="text/html" id="person-template">
<p>Name: <span data-bind="text: name"></span></p>
<p>
Is On Facebook ?
<input type="checkbox" data-bind="checked: IsOnFacebook" />
</p>
</script>
<script type="text/javascript">
var ppl = [
{ name: 'Pouyan', IsOnFacebook: ko.observable(true) },
{ name: 'Reza', IsOnFacebook: ko.observable(false) }
];
function MyViewModel() {
this.people = ko.observableArray(ppl),
this.toggle = function () {
for (var i = 0; i < ppl.length; i++) {
ppl[i].IsOnFacebook = false;
}
}
}
ko.applyBindings(new MyViewModel());
</script>
when I press the button I want to make changes in People.IsOnFacebook property. the changes will be made successfully but the UI does not show.
You should call it like a function. Like:
ppl[i].IsOnFacebook(false);
This because the ko.observable() returns a function. It's not a property you call anymore but a function call. So in the background they will update your UI. To retreive a property that is observable. You should also use the function call.
Please see this tutorial: http://learn.knockoutjs.com/#/?tutorial=intro