In Processing web service data, Why m.prop is not required? - mithril.js

Note that this getter-setter holds an undefined value until the AJAX
request completes.
var users = m.prop([]); //default value
var doSomething = function() { /*...*/ }
m.request({method: "GET", url: "/user"}).then(users).then(doSomething)
But following code is not used m.prop. Why?
Are you set the default value in a different way?
//model
var User = {}
User.listEven = function() {
return m.request({method: "GET", url: "/user"}).then(function(list) {
return list.filter(function(user) {return user.id % 2 == 0});
});
}
//controller
var controller = function() {
return {users: User.listEven()}
}
If ok in the above code, and useless in the following?
var doSomething = function() { /*...*/ }
m.request({method: "GET", url: "/user"}).then(doSomething)
https://lhorie.github.io/mithril/mithril.request.html

The listEven code works because both m.prop and m.request returns a GetterSetter, but when using m.request the GetterSetter will be populated with the value returned from the promise. It's quite convenient.
And in the last example there is no GetterSetter involved, it's a simple promise usage. So all three examples works fine. To decide which one is best, you have to look at your specific case.

Related

Updating MVC Model List using Knockout.js

I am working on an app which connects to XSockets via WCF and am able to get the data on the client side. I want to display this data using Grid.Mvc and have seen samples of using knockout.js, but I am not sure how to push this into my IEnumerable model so that I can see the View updated.
I have tried using the following code
#{
var initialData = new JavaScriptSerializer().Serialize(Model); }
$(function() {
ws = new XSockets.WebSocket("ws://127.0.0.1:4502/Book");
var vm = ko.mapping.fromJSON('#Html.Raw(initialData)');
ko.applyBindings(vm);
//Just write to the console on open
ws.bind(XSockets.Events.open, function (client) {
console.log('OPEN', client);
ws.bind('SendBook', function (books) {
jQuery.ajax({
type: "POST",
url: "#Url.Action("BooksRead", "Home")",
data: JSON.stringify(books),
dataType: "json",
contentType: "application/json",
success: function (result) {
//This doesnt work
/vm.push({Name:'Treasure Island',Author:'Robert Louis Stevenson'});
//vm.pushAll(result)
},
error: function (result){},
async: false
});
});
});
I am always receiving a null value for the parameter in the the BooksRead JsonResult method.
The model is a simple one
public class BookModel
{
public string Name {get; set;}
public string Author {get; set;}
}
I am returning a BookModel IEnumerable as my Model from the home controller on load and would want to insert new books into it as I receive them in the socket bind. This is because I am using it to generate the grid.
#Html.Grid(Model).Columns(c =>
{
c.Add(b => b.Name).Titled("Title");
c.Add(b => b.Author);
})
I would appreciate any pointers and guidance as to how I can go about achieving this.Many thanks
UPDATE
I am now able to get values in the controller action method after removing the dataType & contentType parameters from the ajax call. The controller method is as follows
public JsonResult BooksRead(string books)
{
BookModel data = JsonConvert.DeserializeObject<BookModel>(books);
List<BookModel> bookList = (List<BookModel>) TempData["books"];
if (bookList != null && data != null)
{
bookList.Add(data);
var bookString = JsonConvert.SerializeObject(bookList);
return Json(bookString);
}
return Json("");
}
I have added a vm.push call in the success handler and am passing the result value to it, but it still doesnt seem to add the new book in the Model. It seems I am doing it the wrong way as I am new to knockout js, jquery & ajax and trying to learn as I go along so please pardon my ignorance
UPDATE 2
I have made a few more changes.Like Uffe said, I have removed the Ajax call. I am adapting the StockViewModel from the StockTicker example to my BookViewModel and have added a parameter to the ctor to take in my IEnumerable model. This works & the item is added. The AddOrUpdate is working fine too & the objects are added to the collection but how can I get my model to be updated in the grid.
#{
var initialData = #Html.Raw(JsonConvert.SerializeObject(Model));
}
$(function() {
vm = new BookViewModel(#Html.Raw(initialData));
ko.applyBindings(vm);
ws = new XSockets.WebSocket("ws://127.0.0.1:4502/Book");
//Just write to the console on open
ws.bind(XSockets.Events.open, function(client) {
console.log('OPEN', client);
ws.bind('SendBook', function (msg) {
vm.AddOrUpdate(msg.book);
});
ws.bind(XSockets.Events.onError, function (err) {
console.log('ERROR', err);
});
});
});
The ViewModel is as follows
var BookViewModel = function(data) {
//this.Books = ko.observableArray(data);
this.Books = ko.observableArray(ko.utils.arrayMap(data, function(book) {
return new BookItem(book);
}));
this.AddOrUpdate = function(book) {
this.Books.push(new BookItem(book));
};
};

Sencha Touch: setValue on TextField does not work

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);
.....
....
...
..
.

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();

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)
}
});