Sencha Touch: setValue on TextField does not work - sencha-touch

In Sencha Touch 2 I have a controller which calls a custom 'prepopulate' method on button tap:
Ext.Ajax.request
({
method: 'GET',
url: myurl, //defined outside
withCredentials: true,
headers:{Authorization : auth},
success: function(response){
var data;
if(response.responseText.length > 0)
data = Ext.JSON.decode(response.responseText.trim());
console.log(data);
var fv = me.getFiscal();
console.log(fv);
fv.prepopulate(data);
Ext.Viewport.animateActiveItem('fiscal', me.getSlideLeftTransition());
},
failure: function(response){
Ext.Msg.alert('Server Error', 'Server down :( please try again later');
}
}
);
View code:
prepopulate : function (data) {
var me = this;
var companyTextField = me.down('#fiscalForm').down('#companyTextField');
var vatField = me.down('#fiscalForm').down('#vatField');
var fiscalCodeTextField = me.down('#fiscalForm').down('#fiscalCodeTextField');
var addressTextField = me.down('#fiscalForm').down('#addressTextField');
var cityTextField = me.down('#fiscalForm').down('#cityTextField');
var zipTextField = me.down('#fiscalForm').down('#zipTextField');
var countryTextField = me.down('#fiscalForm').down('#countryTextField');
console.log(vatField);
console.log((data.vat));
if(data){
if(data.company_name)
companyTextField.setValue(data.company_name);
if(data.vat)
vatField.setValue(data.vat);
if(data.fiscal_code)
fiscalCodeTextField.setValue(data.fiscal_code);
if(data.address)
addressTextField.setValue(data.address);
if(data.city)
cityTextField.setValue(data.city);
if(data.zip)
zipTextField.setValue(data.zip);
if(data.country)
countryTextField.setValue(data.country);
}
console.log(vatField);
}
The AJAX call works fine and it calls on success the prepopulate method passing the data retrieved from the server.
I try to initialize the TextFields using setValue() but the form looks 'brand new' when I open it using the browser
console.log() tells me that the _value private field is correctly set though... I'm groping in the dark right now ... any insight?
Thank You in advance.
M.

As you suggest the data i correctly retrieved and display in the console with the console.log, nonetheless the browser don't find any visible fields to modify the value when the setValue() is called.
The solution so far is to modify the ajax request as follows:
Ext.Ajax.request
({
....
....
success: function(response){
....
Ext.Viewport.animateActiveItem('fiscal', me.getSlideLeftTransition());
//view must be in the viewport before modifying data:
var task = Ext.create('Ext.util.DelayedTask', function () {
var fv = me.getFiscal();
fv.prepopulate(data);
});
task.delay(1000);
.....
....
...
..
.

Related

Jqgrid change nav properties on callback function

i try to change the navbar properties on a jqgrid in a callback function without succes.
The grid is display afeter user is chosing a period. Depend on either the period is open or close user can or cannot edit, add, delete rows. So the navbar need to change properties dynamically.
My code look like that:
$('#mygrid').jqGrid({
// some properties of my grid that works fine
pager : '#gridpager'
});
$("#mygrid").bind("jqGridLoadComplete",function(){
$.ajax({
url: 'checkifperiodopen.php',
data: {
$("#period").val()
},
success: function(data){
if(period==='open'){
jQuery("#mygrid").jqGrid('navGrid','#gridpager',{add:false,edit:false,del:true,search:true,refresh:true});
}
if(period==='close'){
jQuery("#mygrid").jqGrid('navGrid','#gridpager',{add:true,edit:true,del:true,search:true,refresh:true});
}
}
});
});
$('#validChossenPeriod').click(function () {
ajax call to get data on choosen period
success:function(data){
$("#mygrid").jqGrid('clearGridData');
$("#mygrid").jqGrid('setGridParam', { datatype: 'local'});
$("#mygrid").jqGrid('setGridParam', { data: data});
$("#mygrid").trigger('reloadGrid');
}
});
I finally found the answer by show or hide the div that include the navgrid button:
grid = $("#mygrid");
gid = $.jgrid.jqID(grid[0].id);
var $tdadd = $('#add_' + gid);
var $tdedit = $('#edit_' + gid);
var $tddel = $('#del_' + gid);
$("#mygrid").jqGrid('navGrid','#gridpager',{add:true,edit:true,del:true,search:true,refresh:true});
condition if false =
$tdadd.hide();
$tdedit.hide();
$tddel.hide();
if true =
$tdadd.show();
$tdedit.show();
$tddel.show();
Why so complex? There is a other clear way to do this
var view_buttons = true;
if(condition_to_hide) {
view_buttons = false;
}
$("#mygrid").jqGrid('navGrid','#gridpager', { add:view_buttons, edit:view_buttons, del:view_buttons, search:true, refresh:true});

Knockoutjs - function inside viewmodel causing undesirable recursion

In my Knockout view model I have a Save() function which sends a jQuery POST request. Inside this POST request is a call to ko.toJS(this).
Whenever I call this Save function the browser becomes unresponsive and eventually tells me that there's too much recursion. Upon debugging (by using breakpoints), I found that when I call toJS() it appears to do some degree of cloning of the object, and in doing this cloning it calls the Save() function, which in turn calls toJS()... and there's the recursion.
Why exactly does this happen, and is there a way to avoid it without using toJSON()?
[I have another question regarding toJSON, and which explains why I don't want to use it.]
For the sake of completeness, here is my view model.
function vmDictionary(dict) {
if (dict === null || dict === undefined) {
return;
}
var self = this;
// directly-assigned variables
self.Concepts = new vmConcepts(dict.Concepts);
self.Deleted = ko.observable(dict.Deleted);
self.Description = ko.observable(dict.Description);
self.IncludeInSearch = ko.observable(true);
self.ID = ko.observable(dict.ID);
self.Languages = ko.observableArray(dict.Languages);
self.LastUpdate = new vmChangeRecord(dict.LastUpdate);
self.Name = ko.observable(dict.Name);
self.Public = ko.observable(dict.Public);
self.TemplateName = function(observable, bindingContext) {
return "dictionary-template";
};
// computed variables
self.PublicText = ko.computed(function() {
return sp.Utils.Localize(self.Public
? "Public"
: "Private");
});
// exposed functions
self.Save = function () {
$.ajax({
data: ko.toJSON(self),
dataType: "json",
type: "POST",
url: [...],
statusCode: {
200: function (response) {
console.log(response);
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log(xmlHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
};
}
UPDATE: added the entire view model (above).
You must be doing something wrong, works in a little fiddle for me
http://jsfiddle.net/brN9s/
ViewModel = function() {
this.someData = ko.observable("Test");
this.dto = ko.observable();
};
ViewModel.prototype = {
Save: function() {
this.dto(ko.toJS(this));
}
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
viewModel.Save();

How to call a JQuery widget function from ajax success?

I'm trying to call a widget function from success node of an ajax call, however, I'm having no success with it.
My app allows users to add some markers on googlemaps with some description. It is using JQuery-addresspicker widget and Rails. I added a function responsible for adding a marker, it displays a form with a description textarea and a button to submit the information. So, after user submits, the app calls an Ajax function to store user's data and if successfully, I want to call another widget function, just for close InfoWindow, for example.
The problem is, I don't know how to call another widget function from success Ajax node.
JQuery-addresspicker.js
.
.
.
_addFormListener: function(map, marker) {
var form = $(".add-form").clone().show();
var infoWindowContent = form[0];
var infoWindow = new google.maps.InfoWindow({
content: infoWindowContent
});
google.maps.event.addListener(marker, "click", function() {
infoWindow.open(map, this);
});
form.submit(function (event){
event.preventDefault();
var description = $("textarea[name=description]", this).val();
var latitude = marker.getPosition().lat();
var longitude = marker.getPosition().lng();
var data = {
description : description,
latitude : latitude,
longitude : longitude
};
$.ajax({
type : "POST",
url : "/places",
data: {place: data},
beforeSend: function(x) {
x.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},
success: function(x) {
this._closeFormFields(); // Not working!
}
});
});
},
_cleanFormFields: function() {
console.log("testing");
}
.
.
PlacesController
def create
#place = Place.new(params[:place])
if #place.save
redirect_to places_path
else
render :status => 422
end
end
The browser's console raises "Uncaught TypeError: Object [object Window] has no method '_cleanFormFields'
Any ideas? Thanks!
The problem here is the scope of this - the ajax call overwrites this to reference the ajax call object and you loose the widget reference.
To fix this, just add a variable to store the reference to the widget like
form.submit(function (event){
event.preventDefault();
var description = $("textarea[name=description]", this).val();
var latitude = marker.getPosition().lat();
var longitude = marker.getPosition().lng();
var data = {
description : description,
latitude : latitude,
longitude : longitude
};
//new widget reference var (this here still refers to the widget)
var widget = this;
$.ajax({
type : "POST",
url : "/places",
data: {place: data},
beforeSend: function(x) {
x.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},
success: function(x) {
//now use the var widget here
widget._closeFormFields(); // Works!
}
});
});

this.store.create wont fire inside ajax call

I simply am trying to update local storage but inside the Ext.Ajax.request I cant call this.store.create(). How do I call the this.store.create function inside the success: area of the Ajax call. Many thanks for your help.
login: function(params) {
params.record.set(params.data);
var errors = params.record.validate();
if (errors.isValid()) {
var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();
//now check if this login exists
Ext.Ajax.request({
url: '../../ajax/login.php',
method: 'GET',
params: params.data,
form: 'loginForm',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
myMask.hide();
//success they exist show the page
if(obj.success == 1){
//this doesn't work below
this.store.create(params.data);
this.index();
}
else{
Ext.Msg.alert('Incorrect Login');
}
},
failure: function(response, opts) {
alert('server-side failure with status code ' + response.status);
myMask.hide();
}
});
}
else {
params.form.showErrors(errors);
}
},
In Javascript, 'this' keyword changes its meaning with the context it appears in.
When used in a method of an object, 'this' refers to the object the method immediately belong to. In your case, it refers to the argument you passed to Ext.Ajax.request.
To work around this, you need to keep an reference of the upper level 'this' in order to access its 'store' property in an inner context. Specifically, it looks like this:
var me = this,
....;
Ext.Ajax.Request({
...
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
myMask.hide();
//success they exist show the page
if(obj.success == 1){
me.store.create(params.data);
this.index();
}
else{
Ext.Msg.alert('Incorrect Login');
}
},
});

extjs checkbox grid delete rails

i am using ExtJS with Rails...I am trying to delete records selected in grid through "Checkbox column"...i dnt have any idea as to how can i handle "Array" of selected records of grid through rails controller...plzz guide me...
the code on delete button is as follows :
var sm = prodgrid.getSelectionModel();
delbtn.on("click", function () {
var sel = sm.getSelections();
Ext.Ajax.request({
url: 'products/delete',
// method:'DELETE',
params: {
'prodid': sel
}
});
});
How can i iterate through "sel" array in my Rails controller?? plzz help
use Ext.each to iterate an array :
var sm = prodgrid.getSelectionModel();
delbtn.on("click", function () {
var sel = sm.getSelections();
Ext.each(sel,function(data){
/// your stuff
Ext.Ajax.request({
url: 'products/delete',
// method:'DELETE',
params: {
'prodid': data.id // the parameter
}
});
///// end
},this);
});
You cannot pass arrays into Rails controller directly. This article should help you in understanding parameter passing into rails controllers.
That said, you need to convert the array into a string. You can use a function similar to this for converting the array to string:
function array_params(arry) {
var paramvar = "";
arry.each(function(s){
paramvar = paramvar.concat("arr[]=",s,"&");});
paramvar = paramvar.replace(/&$/,"");
return paramvar;
}
and finally call:
Ext.Ajax.request({
url: 'products/delete',
// method:'DELETE',
params: {
'prodid': array_params(sel)
}
});