How do you save objects into a google Ui instance. - javascript

What I want to do is save a data-table and an array in the UI instatance, so that the Handler can call on them to do what it is supposed to do. I am fairly new to programming so don't feel bad if you treat this like a stupid question, but please still answer it. Thank you.

One of the easiest way is to use a hidden widget to store data as string like in this example :
function doGet() {
var app = UiApp.createApplication();
var hidden = app.createHidden('hidden').setId('hidden');// widget's name = hidden
//...
var array = ['item1','item2'] ;
hidden.setValue(array.toString()); //assign a value as a string
//...
return app
}
function handlerfunction(e){
var array = e.parameter.hidden.split(','); // get the widget's value by its name parameter and reconvert it back to an array
//...
return app
}

Related

Force KO to update automatically

So I have two viewModels, one has a document style database in an observable:
var databaseViewModel = function () {
var self = this;
self.database = ko.observableArray([]).publishesTo("database");
}
var calcViewModel = function () {
var self = this;
self.replicatedDatabase = ko.observableArray([]).subscribeTo("database");
}
These get applied thusly:
ko.applyBindings({
databaseViewModel: new databaseViewModel(),
calcViewModel: new calcViewModel()
});
The only problem is, that the drop down box tied to replicatedDatabase doesn't show any items. I know I can force a binding update:
database.valueHasMutated();
But I don't know where and when.
I have tried after the ko.applyBindings however, I'm not sure how to access the newly created databaseViewModel. I've tried inside databaseViewModel after it has been created, but I believe that KO automatically updates the bindings when they've been binded, so not sure this actually makes a difference, it didnt on the dropdowns anyways.
I'm not really sure what I should be doing here.
For reference, I'm using knockout-postbox to do message bus style communications, subscribeTo and publishesTo. So as soon as the database observable is changed it will notify all subscribers, so I thought that maybe replicatedDatabase would have been update in the instance that databaseViewModel was initiated.
So, rather than force knockout to update the values I chose a different approach.
Realistically speaking the page would initially be populated with some data from a server, so with this in mind I proceeded by making a global variable holding the initial data:
var serverData = [{}];
Then just simply populate the observableArray's using Ryan Niemeyer mapping function:
ko.observableArray.fn.map = function ( data, Constructor) {
var mapped = ko.utils.arrayMap(data, function (item) {
return new Constructor(item);
});
this(mapped);
return this;
};
This way both viewModel's start off with the initial data, and when the database viewModel gets updated this permeates through to the other viewModel's

Update Knockout-based Form from javascript object

Is it possible to use Knockout ONLY for viewing/using other objects of custom class?
I'm trying to find a way to open knockout with different data but always the same structure.
What I did:
// I have an Event class which looks like that:
function cEvent(id){
this.id = id;
}
// I keep an array of instances of that class in something like:
var arr = [new cEvent(1), new cEvent(2)]
On the html page I have:
Event ID: <span data-bind="text: id"></span>
I created an accessor-like class to get data from a specific event with Knockout
cEvent2 = function cEvent2(baseEvent) {
this.id = ko.computed(function(){
return baseEvent.id;
});
}
When I use ko.applyBindings(arr[0]); it works but what if I want to load another "model" without cleaning nodes and reapplying knockout on the page?
What I want:
I'd like to have something like ko.applyBindings(arr[1]); that would update the interface based on the data I want.
Of course in reality the cEvent class is much more complex, but I am trying to see if we're able to get something done without directly extending these instances of cEvent with knockout.
Maybe I'm just trying to do something wrong and it's not the way knockout want to work? I know that in my case I want knockout to serve as a "simple class reader" even if it could do more.
Any tip would be really appreciated.
Here's what I would do:
function cEvent(id){
this.id = id;
}
function myViewModel() {
var arr = [new cEvent(1), new cEvent(2)]
this.selectedEvent = ko.observable(arr[0]);
}
ko.applyBindings(new myViewModel());
That way, if you bind to selectedEvent.id all you need to do when you want to view a different event is update the selectedEvent property and all of your bindings will be automatically updated.

How to declare a JavaScript list variable to populate later?

This is my first stab at trying to create a JavaScript object. I am attempting to extract properties from a very complex JSON response from a USGS REST service and save them as an object for later use.
What I am attempting to do is create an empty array as the first property of the object to later populate with instances of a custom object later, the last line of actual code. After digging around both the W3C, MDN and this site, I have yet to really come up with a solution.
Please feel free to not only offer solutions to the array issue, but also offer constructive criticism on the rest of the code. After all, I am trying to learn with this project.
// create site object
function Site(siteCode) {
this.timeSeriesList = [];
this.siteCode = siteCode
this.downloadData = downloadData;
// create timeSeries object
function TimeSeries(siteCode, variableCode) {
this.siteCode = siteCode;
this.variableCode = variableCode;
this.observations = [];
}
// create observation object
function TimeSeriesObservation(stage, timeDate) {
this.stage = stage;
this.timeDate = timeDate;
}
// include the capability to download data automatically
function downloadData() {
// construct the url to get data
// TODO: include the capability to change the date range, currently one week (P1W)
var url = "http://waterservices.usgs.gov/nwis/iv/?format=json&sites=" + this.siteCode + "&period=P1W&parameterCd=00060,00065"
// use jquery getJSON to download the data
$.getJSON(url, function (data) {
// timeSeries is a two item list, one for cfs and the other for feet
// iterate these and create an object for each
$(data.value.timeSeries).each(function () {
// create a timeSeries object
var thisTimeSeries = new TimeSeries(
this.siteCode,
// get the variable code, 65 for ft and 60 for cfs
this.variable.variableCode[0].value
);
// for every observation of the type at this site
$(this.values[0].value).each(function () {
// add the observation to the list
thisTimeSeries.observations.push(new TimeSeriesObservation(
// observation stage or level
this.value,
// observation time
this.dateTime
));
});
// add the timeSeries instance to the object list
this.timeSeriesList.push(thisTimeSeries);
});
});
}
}
If you would like to view the JSON I am using for testing, you can find it here: http://waterservices.usgs.gov/nwis/iv/?format=json&sites=03479000&period=P1W&parameterCd=00060,00065
Thank you in advance for your time and mentoring!
Your primary problem is that this inside the AJAX callback isn't your object, it's variably either the jqXHR object created by jQuery or the current element that you're iterating over with .each.
The simplest solution is to create another reference to this in the higher level lexical scope that may be accessed from inside the inner functions:
var self = this;
$.getJSON(..., function() {
// use self inside to refer to your object
});

Creating a jquery dialog as an API

In my current application I am using jquery UI dialog at many places , so I am planning to create a method like
var MYAPP = MYAPP || {};
MYAPP.overlay = (function(){
$("#id").dialog();
}());
This is my idea but now the problem is my overlay is used for different purpose like overlay form, video, confirmation message etc. Is there a way I can have all the option inside my API . so I just have to call MYAPP.overlay("video",some other parameter) and it will create the overlay without have to repeat the code again and again....any idea or suggestion will be appreciated..
I'm not sure what you are trying to accomplish with the immediately executing anonymous function, but you can do something like this:
MYAPP.overlay = function MYAPP$overlay(id, paramsObj) {
// do something based on element type, id, or params obj here.
$(id).dialog();
// possibly return something if needed.
};
yes you can use parameters. here is a very generic way of doing it:
MYAPP.overlay = (function(){
// complex code ....
return function(arg) {
alert(arg);
}
})();
// example
MYAPP.overlay('hello');
will alert hello

How do I access data in this javascript MAP object?

I'm making an AJAX call which returns XML data, and this is my 'success:' function (callback):
success: function (data) {
var $rowArray = $(data).find("[nodeName=z:row]");
$rowArray.each(function(index) { // for each date put it into calMap.
calMap[$(this)[index].title] = $(this).attr("ows_Title");
calMap[$(this)[index].date] = $(this).attr("ows_EventDate");
});
}
calMap is a global javascript object declared outside of the function.
var calMap = {};
What I want to do is create a function where I can pass in a title, have it search calMap for that title, and if found, the specific object is returned and I'll be able to access the date property for that object.
Problem is, I can't seem to access the data I insert into the calMap object. For starters, I just want to print the map. Tried eval'ing it, tried alerting calMap[0], tried alerting calMap[0].title, but nothing. Can someone help me with this? Thanks!
Update:
I want to do something like this:
var data = getData("myTitle");
function getData(title) {
// if title is in calMap, something like this?
var result = (calMap[title]));
return result; // returns an object or NOTHING
}
then i'll check if date is defined or not, and if it is, i'll access its properties (ie. data.date. That make sense?
ANSWER:
I ended up using an array. STILL think I should be able to use the object MAP, but needed to get my project done.
Here's the final code for the code that accesses the array items:
function hasCalDate(code)
{
var matched = "";
for (var f=0;f<calMap.length;f++){
var re = new RegExp(code);
if (re.test(calMap[f].title))
{
matched = calMap[f].title+','+calMap[f].date;
}
}
return matched;
};
Thanks everyone.
You need to initialize calMap as an array (i.e. square brackets, not curly ones):
var calMap = [];
Then, inside your each function, I'm guessing you want something more like
calMap.push({
title: $(this).attr("ows_Title"),
date: $(this).attr("ows_EventDate")
});
Your problem is that the success function is only run when your AJAX request completes. If you want to access calMap safely, you need to do so inside your callback.

Categories

Resources