I have an interesting situation. I am creating an Enhanced Datagrid (ith about 24000 entries). So I am planning to load a small subset to display some data to user while another request finishes. you can see what I am trying to do in code below. Now issue is, both these functions in "load" will update grid datastore. I want to make sure that updateDataStore() from second xhrGet is called ONLY after createDataStore() is finished. This is required because I am creating ids dynamically for rows in data store.
I do not want to hold second xhrGET request till first xhrGET is completed.
** code to update store**
var ds = dijit.byId("grid").store;
ds.newItem();
code to create grid and make two xhrGET requests
CreateEmptyGrid();
dojo.require("dojo._base.xhr");
dojo.xhrGet({
url:"url1",
handleAs:"json",
load: function(data){createDataStore(data);
}
});
dojo.xhrGet(
{
url:"url2",
handleAs:"json",
load: function(data){updateDataStore(data);}
});
Here an example with DeferredList
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:scriptBlock id="scriptBlockPromises">
<xp:this.value><![CDATA[
require(["dojo/request", "dojo/DeferredList"], function(request, DeferredList) {
var responses = new Array();
var promise1 = request("/path/to/data/1").then(function(response) {
createDataStore(response);
});
var promise2 = request("/path/to/data/2").then(function(response) {
responses[0] = response;
});
var list = new DeferredList([promise1, promise2]);
list.then(function(result) {
updateDataStore(responses[0]);
});
});]]></xp:this.value>
</xp:scriptBlock>
</xp:view>
You can nest the second request in the load function of the first:
CreateEmptyGrid();
dojo.require("dojo._base.xhr");
dojo.xhrGet({ url:"url1", handleAs:"json", load: function(data){
createDataStore(data);
dojo.xhrGet( {
url:"url2",
handleAs:"json",
load: function(data){
updateDataStore(data);
}
});
} });
You could use a global variable to get the state of the data store and periodically check if it has been created:
CreateEmptyGrid();
dojo.require("dojo._base.xhr");
hasDataStore=false;
dojo.xhrGet({
url:"url1",
handleAs:"json",
load: function(data){ createDataStore(data); hasDataStore=true; }
});
dojo.xhrGet(
{
url:"url2",
handleAs:"json",
load: function(data){
itvCheckDataStore=setInterval(function() {
if (hasDataStore) {
clearInterval(itvCheckDataStore);
updateDataStore(data);
}
},256);
}
});
I didn't try the code, so I can't say if I might have missed some closing brackets or so.
Related
I'm trying to figure out how to apply the promises infrastructure in the case where I'm looping through a list of portfolio items to extract data for highcharts use and need to retrieve data from the related user stories. The goal is to create a way to not attempt to instantiate the chart object until all async callbacks are completed. Here's a code snippet illustrating what I'm trying to do - in this example, the getCollection() method's callback function is not being executed until all of the outer loop features have been retrieved.
_.each(records, function(feature) {
var rname = (feature.get('Release')) ? feature.get('Release')._refObjectName: "None";
//various other feature record extraction steps
feature.getCollection('UserStories').load({
fetch: ['FormattedID', 'Name', 'InProgressDate','AcceptedDate'],
callback: function(stories, operation, success){
Ext.Array.each(stories, function(story) {
var storyname = story.get('FormattedID') + ': ' + story.get('Name');
// other chart data extraction steps
}
});
}
});
});
I'd check out the guide in the docs on working with promises, especially the section on retrieving hierarchical data:
https://help.rallydev.com/apps/2.0/doc/#!/guide/promises-section-retrieving-hierarchical-data
The basic idea is to keep an array of all the promises representing the child collection store loads and then to use a Deft.Promise.all to wait for them all to finish before continuing.
So something like this, based on your code above:
var childStoryPromises = [];
_.each(records, function(feature) {
var rname = (feature.get('Release')) ? feature.get('Release')._refObjectName: "None";
// various other feature record extraction steps
var userStoriesStore = feature.getCollection('UserStories');
var promise = userStoriesStore.load({
fetch: ['FormattedID', 'Name', 'InProgressDate','AcceptedDate']
});
childStoryPromises.push(promise);
feature.userStoriesStore = userStoriesStore; //save reference for later
});
//wait for all stores to load
Deft.Promise.all(childStoryPromises).then({
success: function() {
_.each(records, function(feature) {
var userStories = feature.userStoriesStore.getRange();
//extract user story data here
});
},
scope: this
});
I ahve an xml store that calls an url and fetch data from database. It has to be displayed in the data grid when there is data returned from the database. When there is no data, it has to show appropriate error message.
I have the following js file.
require(["dojo/date/locale","dojox/grid/DataGrid","dojox/data/XmlStore","dijit/registry", "dojo/fx","dijit/form/ValidationTextBox", "dojo/dom-form", "dojo/dom", "dojo/on", "dojo/request","dojox/xml/parser", "dojo/ready","dojo/domReady!"],
function(locale,DataGrid,XmlStore,registry,coreFx,dijit, domForm, dom, on, request, parser, ready){
var format;
var siteId;
var phoneNum;
var grid;
var dataGrid=new DataGrid({
autoWidth:true,
autoHeight:true,
clientSort:true,
structure: [
{name:"Order ID", field:"orderId"},
{name:"Sender", field:"senderName"},
{name:"Recipient", field:"recipientName"},
{name:"Phone Number", field:"phone"},
{name:"Gift Amount", field:"amount"}
]
},"showGrid");
dataGrid.startup();
on(dom.byId("submitButton"), "click", function(){
ready(function()
{
submitValue();
});
});
on(dom.byId("printGiftcard"), "click", function(){
ready(function()
{
window.print();
});
});
function submitValue(){
grid=registry.byId("showGrid");
grid.set("store", null);
grid.filter();
document.getElementById("outcomeMessage").innerHTML="";
var orderNumber= document.getElementById("orderNumber");
var num=orderNumber.value;
if(num==""){
document.getElementById("outcomeMessage").innerHTML="Please enter Order number";
return;
}
var myStore= new XmlStore({
url:"/hello/"+num,
urlPreventCache : false,
query:{},
queryOptions:{},
onComplete:sizeCount
});
var sizeCount = function(items,request){
console.log(items.length);
if(items.length == 0){
document.getElementById("outcomeMessage").innerHTML="data not found";
}
}
var request = myStore.fetch({query:{},queryOptions:{},onComplete:sizeCount});
grid=registry.byId("showGrid");
grid.set("store", myStore);
//grid.filter();
}
});
The problem is it is calling database twice now in order to check the number of items returned.Once to set the store for the grid and other to check if the data returned is null.Can someone give me a simplified solution for this.
Thanks
I finally resolved my issue.
dojo.connect(dataGrid,"_onFetchComplete",function(items){
console.log(datagrid.rowCount);
}
})
Thanks!
How can we get and post api in Titanium alloy?
I am having the api of userDetails, I just want that how can i code to get the data from api.
function getUserDetails(){
}
Thanks in advance.
As you mentioned, you are using Titanium alloy.
So another approach be to extend the Alloy's Model and Collection ( which are based on backbone.js concept ).
There are already some implementation at RestAPI Sync Adapter also proper description/usage at Titanium RestApi sync.
I also provide the description and methodology used, in-case link gets broken:
Create a Model : Alloy Models are extensions of Backbone.js Models, so when you're defining specific information about your data, you do it by implementing certain methods common to all Backbone Models, therefor overriding the parent methods. Here we will override the url() method of backbone to allow our custom url endpoint.
Path :/app/models/node.js
exports.definition = {
config: {
adapter: {
type: "rest",
collection_name: "node"
}
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
url: function() {
return "http://www.example.com/ws/node";
},
});
return Collection;
}
};
Configure a REST sync adapter : The main purpose of a sync adapter is to override Backbone's default sync method with something that fetches your data. In our example, we'll run through a few integrity checks before calling a function to fetch our data using a Ti.Network.createHTTPClient() call. This will create an object that we can attach headers and handlers to and eventually open and send an xml http request to our server so we can then fetch the data and apply it to our collection.
Path :/app/assets/alloy/sync/rest.js (you may have to create alloy/sync folders first)
// Override the Backbone.sync method with our own sync
functionmodule.exports.sync = function (method, model, opts)
{
var methodMap = {
'create': 'POST',
'read': 'GET',
'update': 'PUT',
'delete': 'DELETE'
};
var type = methodMap[method];
var params = _.extend(
{}, opts);
params.type = type;
//set default headers
params.headers = params.headers || {};
// We need to ensure that we have a base url.
if (!params.url)
{
params.url = model.url();
if (!params.url)
{
Ti.API.error("[REST API] ERROR: NO BASE URL");
return;
}
}
//json data transfers
params.headers['Content-Type'] = 'application/json';
switch (method)
{
case 'delete':
case 'create':
case 'update':
throw "Not Implemented";
break;
case 'read':
fetchData(params, function (_response)
{
if (_response.success)
{
var data = JSON.parse(_response.responseText);
params.success(data, _response.responseText);
}
else
{
params.error(JSON.parse(_response.responseText), _response.responseText);
Ti.API.error('[REST API] ERROR: ' + _response.responseText);
}
});
break;
}
};
function fetchData(_options, _callback)
{
var xhr = Ti.Network.createHTTPClient(
{
timeout: 5000
});
//Prepare the request
xhr.open(_options.type, _options.url);
xhr.onload = function (e)
{
_callback(
{
success: true,
responseText: this.responseText || null,
responseData: this.responseData || null
});
};
//Handle error
xhr.onerror = function (e)
{
_callback(
{
'success': false,
'responseText': e.error
});
Ti.API.error('[REST API] fetchData ERROR: ' + xhr.responseText);
};
for (var header in _options.headers)
{
xhr.setRequestHeader(header, _options.headers[header]);
}
if (_options.beforeSend)
{
_options.beforeSend(xhr);
}
xhr.send(_options.data || null);
}
//we need underscore
var _ = require("alloy/underscore")._;
Setup your View for Model-view binding : Titanium has a feature called Model-View binding, which allows you to create repeatable objects in part of a view for each model in a collection. In our example we'll use a TableView element with the dataCollection property set to node, which is the name of our model, and we'll create a TableViewRow element inside. The row based element will magically repeat for every item in the collection.
Path :/app/views/index.xml
<Alloy>
<Collection src="node">
<Window class="container">
<TableView id="nodeTable" dataCollection="node">
<TableViewRow title="{title}" color="black" />
</TableView>
</Window>
</Alloy>
Finally Controller : Binding the Model to the View requires almost no code at the controller level, the only thing we have to do here is load our collection and initiate a fetch command and the data will be ready to be bound to the view.
Path :/app/controllers/index.js
$.index.open();
var node = Alloy.Collections.node;
node.fetch();
Further reading :
Alloy Models
Sync Adapters
Hope it is helpful.
this is the solution for your problem:-
var request = Titanium.Network.createHTTPClient();
var done=false;
request.onload = function() {
try {
if (this.readyState == 4 && !done) {
done=true;
if(this.status===200){
var content = JSON.parse(this.responseText);
}else{
alert('error code' + this.status);
}
}
} catch (err) {
Titanium.API.error(err);
Titanium.UI.createAlertDialog({
message : err,
title : "Remote Server Error"
});
}
};
request.onerror = function(e) {
Ti.API.info(e.error);
};
request.open("POST", "http://test.com");
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send({ test: 'test'});
if you don't get your answer please let me know.
Thanks
In my ExtJS 4.0.7 app I have some 3rd party javascripts that I need to dynamically load to render certain panel contents (some fancy charting/visualization widgets).
I run in to the age-old problem that the script doesn't finish loading before I try to use it. I thought ExtJS might have an elegant solution for this (much like the class loader: Ext.Loader).
I've looked at both Ext.Loader and Ext.ComponentLoader, but neither seem to provide what I'm looking for. Do I have to just "roll my own" and setup a timer to wait for a marker variable to exist?
Here's an example of how it's done in ExtJS 4.1.x:
Ext.Loader.loadScript({
url: '...', // URL of script
scope: this, // scope of callbacks
onLoad: function() { // callback fn when script is loaded
// ...
},
onError: function() { // callback fn if load fails
// ...
}
});
I've looked at both Ext.Loader and Ext.ComponentLoader, but neither
seem to provide what I'm looking for
Really looks like it's true. The only thing that can help you here, I think, is Loader's injectScriptElement method (which, however, is private):
var onError = function() {
// run this code on error
};
var onLoad = function() {
// run this code when script is loaded
};
Ext.Loader.injectScriptElement('/path/to/file.js', onLoad, onError);
Seems like this method would do what you want (here is example). But the only problem is that , ... you know, the method is marked as private.
This is exactly what newest Ext.Loader.loadScript from Ext.4-1 can be used for.
See http://docs.sencha.com/ext-js/4-1/#!/api/Ext.Loader-method-loadScript
For all you googlers out there, I ended up rolling my own by borrowing some Ext code:
var injectScriptElement = function(id, url, onLoad, onError, scope) {
var script = document.createElement('script'),
documentHead = typeof document !== 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
cleanupScriptElement = function(script) {
script.id = id;
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
return this;
},
onLoadFn = function() {
cleanupScriptElement(script);
onLoad.call(scope);
},
onErrorFn = function() {
cleanupScriptElement(script);
onError.call(scope);
};
// if the script is already loaded, don't load it again
if (document.getElementById(id) !== null) {
onLoadFn();
return;
}
script.type = 'text/javascript';
script.src = url;
script.onload = onLoadFn;
script.onerror = onErrorFn;
script.onreadystatechange = function() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
onLoadFn();
}
};
documentHead.appendChild(script);
return script;
}
var error = function() {
console.log('error occurred');
}
var init = function() {
console.log('should not get run till the script is fully loaded');
}
injectScriptElement('myScriptElem', 'http://www.example.com/script.js', init, error, this);
From looking at the source it seems to me that you could do it in a bit of a hackish way. Try using Ext.Loader.setPath() to map a bogus namespace to your third party javascript files, and then use Ext.Loader.require() to try to load them. It doesn't look like ExtJS actually checks if required class is defined in the file included.
I can't seem to get a handle on my list of sortables. They are a list of list elements, each with a
form inside, which I need to get the values from.
Sortables.implement({
serialize: function(){
var serial = [];
this.list.getChildren().each(function(el, i){
serial[i] = el.getProperty('id');
}, this);
return serial;
}
});
var sort = new Sortables('.teams', {
handle: '.drag-handle',
clone: true,
onStart: function(el) {
el.fade('hide');
},
onComplete: function(el) {
//go go gadget go
order = this.serialize();
alert(order);
for(var i=0; i<order.length;i++) {
if (order[i]) {
//alert(order[i].substr(5, order[i].length));
}
}
}
});
the sortables list is then added to a list in a loop with sort.addItems(li); . But when I try to get the sortables outside of the sortables onComplete declaration, js says this.list is undefined.
Approaching the problem from another angle:
Trying to loop through the DOM gives me equally bizarre results. Here are the firebug console results for some code:
var a = document.getElementById('teams').childNodes;
var b = document.getElementById('teams').childNodes.length;
try {
console.log('myVar: ', a);
console.log('myVar.length: ', b);
} catch(e) {
alert("error logging");
}
Hardcoding one li element into the HTML (rather than being injected via JS) changes length == 1, and allows me to access that single element, leading me to believe that accessing injected elements via the DOM is the problem (for this method)
Trying to get the objects with document.getElementById('teams').childNodes[i] returns undefined.
thank you for any help!
not sure why this would fail, i tried it in several ways and it all works
http://www.jsfiddle.net/M7zLG/ test case along with html markup
here is the source that works for local refernece, using the native built-in .serialize method as well as a custom one that walks the dom and gets a custom attribute rel, which can be your DB IDs in their new order (I tend to do that)
var order = []; // global
var sort = new Sortables('.teams', {
handle: '.drag-handle',
clone: true,
onStart: function(el) {
el.fade('hide');
},
onComplete: function(el) {
//go go gadget go
order = this.serialize();
}
});
var mySerialize = function(parentEl) {
var myIds = [];
parentEl.getElements("li").each(function(el) {
myIds.push(el.get("rel"));
});
return myIds;
};
$("saveorder").addEvents({
click: function() {
console.log(sort.serialize());
console.log(order);
console.log(mySerialize($("teams")));
}
});