sending konckoutjs ViewModel as data throught ajax - json

for populating search form with data i'm using following ViewModel:
function AppViewModel() {
var self = this;
self.Countries =[{"id": "1","name": "Russia"},{"id": "2","name": "Qatar"}];
self.selectedCountryId =ko.observable();
}
I need Countries list for populate dropdwonlist.
When user fills the form and clicks "send", i need to submit the data, but i do not need to send the Countries list!
(only SelectedCountryId)
var vm=new AppViewModel();
ko.applyBindings(vm);
$('button').click(function(){
console.log(ko.mapping.toJSON(vm));
});
Is there the way to get rid of countries list without build new ViewModel for sending?

Observables are just like normal functions, so you just need to call it from outside.
function AppViewModel() {
var self = this;
self.Countries =[{"id": "1","name": "Russia"},{"id": "2","name": "Qatar"}];
self.selectedCountryId = ko.observable('1');
}
$(function() {
var vm = new AppViewModel();
ko.applyBindings(vm);
$('button').click(function(){
console.log(vm.selectedCountryId()); // plain
console.log(ko.toJSON(vm.selectedCountryId())); // json
});
});
​
http://jsfiddle.net/DiegoVieira/6kZMj/4/

Please take a look into this demo I've created for you Click here for the DEMO
Updated Demo Click here for the updated Demo
HTML Code
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice, optionsCaption: 'Choose..'"></select>
<br/>
<label data-bind="text: selectedChoice"></label>
Javascript Code
var CountryModel = function(data){
var self = this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
};
var viewModel = function(data) {
var self = this;
self.selectedChoice = ko.observable();
self.countries = ko.observableArray([
new CountryModel({id: "1", name: "Russia"}),
new CountryModel({id: "2", name: "Qatar"})]);
};
ko.applyBindings(new viewModel());
START UPDATE
What is updated:
HTML Code:
Added button on event Click it calls sendMe function which returns json object of selectedCountryId
<input type="button" data-bind="click: sendMe, enable: selectedChoice" Value="Click Me"/>
Javascript Code
self.sendMe = function(){
alert(ko.toJSON({ selectedCountryId: this.selectedChoice()}));
};
END UPDATE
START UPDATE1
This is update for the last comment, regarding avoid addition model, in this case let's skip CountryModel
So, the Javascript Code will be the following:
var viewModel = function(data) {
var self = this;
self.selectedChoice = ko.observable();
self.countries = ko.observableArray([
{id: "1", name: "Russia"},
{id: "2", name: "Qatar"}]);
self.sendMe = function(){
alert(ko.toJSON({ selectedCountryId: this.selectedChoice()}));
};
};
ko.applyBindings(new viewModel());
END UPDATE1
Hope, it will help you.
Thanks.

Related

AngularJS how to get data from <textarea> prefilled by Google Maps script

I have a script that accesses the Goggle Maps API and fills in a <textarea> with results. How do I pass that prefilled data into an AngularJS controller?
$scope.Add=function(msg){
$log.log(msg)
}
<div ng-app="">
<div ng-controller="MapController">
<div style="display:block">
<div id="map" style="float:left"></div>
<div style="float:left;">
<textarea class="user" ng-model="user" id="points_textarea"></textarea>
<input type="button" value="submit" ng-click="Add(user)" />
</div>
</div>
i am new to angularjs,
how to pass the data from textarea which is already prefilled from one of the javascript function in html, to the controller in angularjs
Any help please
Bring the Google Maps functions into the AngularJS framework:
angular.module("gMap", [])
.service("gMap", function($q) {
var directionsService = new google.maps.DirectionsService();
var map;
var origin = null;
var destination = null;
var waypoints = [];
var markers = [];
this.initialize = initialize;
this.calcRoute = calcRoute;
this.reset = reset;
//functions here
});
Modify the calcRoute function to return a promise:
function calcRoute() {
var mode = google.maps.DirectionsTravelMode.DRIVING;
var request = {
origin: origin,
destination: destination,
waypoints: waypoints,
travelMode: mode,
optimizeWaypoints: true,
avoidHighways: false
};
var pointsDefer = $q.defer();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Code snipped
̶v̶a̶r̶ ̶p̶o̶i̶n̶t̶s̶_̶t̶e̶x̶t̶a̶r̶e̶a̶=̶d̶o̶c̶u̶m̶e̶n̶t̶.̶g̶e̶t̶E̶l̶e̶m̶e̶n̶t̶B̶y̶I̶d̶(̶"̶p̶o̶i̶n̶t̶s̶_̶t̶e̶x̶t̶a̶r̶e̶a̶"̶)̶;̶
̶p̶o̶i̶n̶t̶s̶_̶t̶e̶x̶t̶a̶r̶e̶a̶.̶v̶a̶l̶u̶e̶ ̶=̶ ̶p̶o̶i̶n̶t̶s̶_̶t̶e̶x̶t̶;̶
var pointsObj = {};
pointsObj.routeCenter = response.routes[0].bounds.getCenter();
pointsObj.routeSpan = response.routes[0].bounds.toSpan();
pointsObj.routePoints =
response.routes[0].overview_path
.map( _ => ({
lat: _.lat(),
lng: _.lng()
}));
pointsDefer.resolve(pointsObj);
clearMarkers();
directionsDisplay.setDirections(response);
} else { pointsDefer.reject(status); };
});
return pointsDefer.promise;
}
Notice that the above function removes the code that fills in the <textarea> with the data. Instead the code returns an AngularJS promise that resolves with the data.
Replace the <textarea> in the HTML
<body ng-app="app" ng-controller="ctrl as vm">
<h2>Google Map route point generator</h2>
Click on the map to select the route points (up to 8).
<br/><br/>
<input type="button" value="Get Points" ng-click="vm.calcRoute()" />
<input type="button" value="Reset" ng-click="vm.reset()" />
<br/><br/>
<div id="map_canvas"></div>
<br/>
̶<̶t̶e̶x̶t̶a̶r̶e̶a̶ ̶r̶e̶a̶d̶o̶n̶l̶y̶ ̶i̶d̶=̶"̶p̶o̶i̶n̶t̶s̶_̶t̶e̶x̶t̶a̶r̶e̶a̶"̶ ̶o̶n̶C̶l̶i̶c̶k̶=̶"̶s̶e̶l̶e̶c̶t̶_̶a̶l̶l̶(̶)̶;̶"̶>̶
̶<̶/̶t̶e̶x̶t̶a̶r̶e̶a̶>̶
<br/>
{{vm.points | json}}
</body>
The App
angular.module("app",['gMap'])
.run(function(gMap){
gMap.initialize();
})
.controller("ctrl", function(gMap) {
this.calcRoute = function() {
var promise = gMap.calcRoute();
promise.then( data => {
this.points = data;
})
};
this.reset = function() {
gMap.reset();
this.points = {};
};
})
The DEMO on PLNKR
You can use ng-model and ng-bind for these.
Check this in angular 4 - https://coursetro.com/posts/code/58/Angular-4-Property-Binding-Tutorial
And in Angular 1 - https://docs.angularjs.org/api/ng/directive/ngBind
HTML :
<textarea rows="4">{{user.content}}</textarea>
JS:
var app = angular.module('myApp', []);
app.controller('userCtrl', function($scope) {
$scope.user = {
'content': 'Theming support in an application can be pretty useful.'
};
});
I have made you simple plnkr example
It will show prefilled data and on change of textarea it will show alert
Main thing to understand is ng-model, it is binding your input type="textarea" with variable textArea by using ng-model="textArea"
https://plnkr.co/edit/rml2JC8YZgLDTyLgq7x3?p=preview
You can define your Textarea like this:
<textarea ng-model='test_textarea'></textarea>
Then you should initialize your textarea in controller like this:
$scope.test_textarea = "content";
Your angular app initializes when the documents DOM is ready - thus, overrides the value with your $scope.test_textarea value.

How to get multiple data series into Highcharts

The following code works:
var options1 = {
chart: {
renderTo: 'container1'
},
series: [{}]
};
$.getJSON('tokyo.jsn', function(data){
options1.series[0].data = data;
var chart = new Highcharts.Chart(options1);
});
I want to be able to add a number of data series, so I am trying to take the reference to ‘new Highcharts’ out of the getJSON, but I don't seem to get it right. This following code does not work:
$.getJSON('tokyo.jsn', function(data){
options1.series[0].data = data;
});
var chart = new Highcharts.Chart(options1);
I have also tried tackling it a different way but again the following code does not work:
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container1'
},
series: [{}]
});
$.getJSON('tokyo.jsn', function(data){
chart1.series[0].data = data;
});
Can anyone point me in the correct direction. I need to be able to support multiple data series by doing a second getJSON call like the following:
$.getJSON('sydney.jsn', function(data){
options1.series[1].data = data;
});
The JSON code I'm using is as follows:
[ 7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6 ]
Thanks
$.getJSON is an asynchronous request. Once you receive the data, then you can pass it to Highcharts, thus you have to call that code from within the callback function of $.getJSON().
Try this, use a helper function to process your data and draw the chart, see drawChart() below:
var options1 = {
chart: {
renderTo: 'container1'
},
series: []
};
var drawChart = function(data, name) {
// 'series' is an array of objects with keys:
// - 'name' (string)
// - 'data' (array)
var newSeriesData = {
name: name,
data: data
};
// Add the new data to the series array
options1.series.push(newSeriesData);
// If you want to remove old series data, you can do that here too
// Render the chart
var chart = new Highcharts.Chart(options1);
};
$.getJSON('tokyo.jsn', function(data){
drawChart(data, 'Tokyo');
});
$.getJSON('sydney.jsn', function(data){
drawChart(data, 'Sydney');
});
See fiddle: http://jsfiddle.net/amyamy86/pUM7s/
You can use solution used by Highcharts in that example: http://www.highcharts.com/stock/demo/compare
Or first create empty chart, without any series, and then use addSeries() function in each callback, see: http://api.highcharts.com/highcharts#Chart.addSeries()

Load JSON file to Backbone collection

Hi I'm looking for proper solution to load JSON to Backbone collection. I saw a lot of post with this problem, but I still don't understand how to do it correctly.
For example, Could You explain me please why this project doesn't work?
http://blog.joelberghoff.com/2012/07/22/backbone-js-tutorial-part-1/
Edit:
When I look at the results using Firebug, it shows me an empty object, collection is empty.
Why?
EDIT:
hmmm, still doesn't work :/ Now I don't see anything in firebug and one the page. :(
$(function() {
var Profile = Backbone.Model.extend();
var ProfileList = Backbone.Collection.extend({
model: Profile,
url: 'profiles.json'
});
var ProfileView = Backbone.View.extend({
el: "#profiles",
template: _.template($('#profileTemplate').html()),
render: function(eventName) {
_.each(this.model.models, function(profile){
var profileTemplate = this.template(profile.toJSON());
$(this.el).append(profileTemplate);
}, this);
return this;
}
});
var profiles = new ProfileList();
var profilesView = new ProfileView({model: profiles});
var profiles = new ProfileList();
profiles.fetch();
profiles.bind('reset', function () {
console.log(profiles);
profilesView.render();
});
});
Your fetch call is asynchronous, as I'm sure it's written in the tutorial. So when you're doing the console.log, your collection is still empty.
Farther in the tutorial..:
var profiles = new ProfileList();
profiles.fetch({reset: true});
profiles.bind('reset', function () { console.log(profiles); });
This should work.

KnockoutJS - Databind to a dictionary collection - with update

This this question here
KnockoutJS - Databind to a dictionary collection
I'm creating a drop down select from JSON coming from the server.
However at some point after creating it I wish to update the data.
I've created a fiddle
http://jsfiddle.net/LPrf3/
Which shows where I'm at at present. I successfully update the select's observable array.
However... for some reason you need to click into the select from the drop down in order for it to refresh
Javascript:
$(function() {
var destinationsFromServer = {"Europe":"Europe incl Egypt, Turkey & Tunisia","ANZO":"Australia & New Zealand","WorldwideUSA":"Worldwide (incl USA & Canada)"};
var updatedDestinationsFromServer = {"Arctic":"Includes Polar bears and seals","Antarctic":"Just Penguins"};
function mapDictionaryToArray(dictionary) {
var result = [];
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
result.push({ key: key, value: dictionary[key] });
}
}
return result;
}
function viewModel () {
destinations= ko.observableArray(mapDictionaryToArray(destinationsFromServer));
selectedDestination= ko.observable();
updateDestinations = function()
{
destinations= ko.observableArray(mapDictionaryToArray(updatedDestinationsFromServer));
};
};
ko.applyBindings(new viewModel());
});
HTML
<select data-bind="options: destinations, optionsText: 'key', optionsValue: 'value', value: selectedDestination"></select>
<hr />
<div data-bind="text: selectedDestination"></div>
<button data-bind="click:updateDestinations">UPDATE</button>
How can I get the select to update?
You are reassinging destinations to a new observabelArray instead of updating the array. See this fiddle. When updating any observable, always pass the new value in as a parameter, never assign a new value with the = operatior.
Wrong Way:
updateDestinations = function(){
destinations=ko.observableArray(mapDictionaryToArray(updatedDestinationsFromServer));
};
Right Way:
updateDestinations = function(){
destinations(mapDictionaryToArray(updatedDestinationsFromServer));
};

Drag & Drop HTML 5 jQuery: e.dataTransfer.setData() with JSON

Here it is my dragstart:
dragstart: function(e) {
$(this).css('opacity', '0.5');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('application/json', {
id: $(this).attr('id'),
header: $('header', this).text()
});
},
I would like to pass some informations such id and text. My drop is:
drop: function(e) {
var data = e.dataTransfer.getData('application/json');
alert(data);
$(this).attr('id', data.id);
$('header', this).text(data.header);
},
But data is undefined, I can't access to my data. Is it the right way?
Thank's!
in drag start
var testjson = {name:"asd",tall:123};
e.dataTransfer.setData("text/plain",JSON.stringify(testjson));
e.dataTransfer.effectAllowed = "copy";
in drop
var data = e.dataTransfer.getData("text/plain");
console.log(JSON.parse(data));
and u will get
Object {name: "asd", tall: 123}
in console.log
If you include an effectAllowed in your dragstart function, such as:
e.dataTransfer.effectAllowed = 'move';
Then it is my understanding that you need to define an equivalent dropEffect in the drop function :
e.dataTransfer.dropEffect = 'move';