Using Handlebars.js with StackMob - javascript

What I'm trying to do is when the page is loaded it will show the user a list of all their "contacts". There is a fair bit of code so I put it all HERE and below is just the load method.
$(window).load(function () {
var Contacts = StackMob.Model.extend({ schemaName: 'contacts' });
var myContacts = new Contacts();
var q = new StackMob.Collection.Query();
q.orderAsc('firstname'); //sort by firstname in ascending order
myContacts.query(q, {
success: function (model) {
console.log(model.toJSON());
for (var i = 0; i < model.length; i++) {
var data = ({
FirstName: model[i].attributes.firstname,
LastName: model[i].attributes.lastname,
Pno: model[i].attributes.phoneno,
Emails: model[i].attributes.email,
objIdel: model[i].contacts_id,
objIdeit: model[i].contacts_id
});
var template = Handlebars.compile($('#template').html());
var html = template(model);
$("#contacts").append(template(data));
}
},
error: function (model, response) {
console.debug(response);
}
});
});
console.log(model.toJSON()); shows what I would expect but It doesn't seem to be getting into the for loop at all.
EDIT: If i get rid of the loop and use the code below I get only one contact with no values in the inputs
var data = ({
FirstName: model.attributes.firstname,
LastName: model.attributes.lastname,
Pno: model.attributes.phoneno,
Emails: model.attributes.email,
objIdel: model.contacts_id,
objIdeit: model.contacts_id
});
EDIT: I was able to get the firstname of a contact using console.log(results.attributes[0]["firstname"]); the problem is I cant figure out why its not going into the loop.
I tested the code without the loop and it made a handlebars template of the first contact that worked as planed, but I cant figure out why it wont loop through them all.
Link to a more up to date version of the code

How about trying this ... I iterate over the jsonData to get each object. Not sure if handlebars expects a JSON object or the JSON string, so I output each to the console.log
var Contact = StackMob.Model.extend({ schemaName: 'todo' });
var Contacts = StackMob.Collection.extend({ model: Contact });
var q = new StackMob.Collection.Query();
q.orderAsc('name'); //sort by firstname in ascending order
var myContacts = new Contacts();
myContacts.query(q, {
success: function (data) {
jsonData = data.toJSON();
for (var i = 0; i < data.length; i++) {
var obj = jsonData[i];
console.log(obj);
console.log(JSON.stringify(obj));
}
},
error: function (model, response) {
console.debug(response);
}
});

Related

Unable to update row by objectId using Parse core javascript

I am unable to update row by object id in parse. I am using parse javascript sdk. Below is the code that i tried, but unable to update the column "read" to true. So my code pass in a threadId and user object to get all the comments of the user under the thread. What i want to do is to mark all the comments as read = true. I am not sure why this code is not working? any idea how i can update my rows?
readAllById: function(threadId , user){
var ParseString = Parse.Object.extend("Comments");
var query = new Parse.Query(ParseString);
query.equalTo("threadId", threadId);
query.equalTo("user" , user);
query.ascending("createdAt");
query.include("user");
query.include("item");
return query.find().then(function(response){
for(var i = 0; i < response.length; i++ ) {
console.log(response[i]);
var object_id = response[i].id;
query.set("id", object_id);
query.set("read", true);
query.save();
}
}, function(error){
//something went wrong!
});
},
Okay. I got it working by using this code below
readAllById: function(threadId , user){
var ParseString = Parse.Object.extend("Comments");
var query = new Parse.Query(ParseString);
query.equalTo("threadId", threadId);
query.equalTo("user" , user);
query.ascending("createdAt");
query.include("user");
query.include("item");
return query.find().then(function(response){
for(var i = 0; i < response.length; i++ ) {
var result = Parse.Object.extend("Comments");
var result = new Parse.Query(result);
query.get(response[i].id,{
success: function(result) {
result.set('read', true);
result.save();
}
});
}
}, function(error){
//something went wrong!
});
},

Parse.Cloud.job promise not working

What I am trying to do here are:
Remove all contents in a class first, because every day the events.json file will be updated. I have my first question here: is there a better way to remove all contents from a database class on Parse?
Then I will send a request to get the events.json and store "name" and "id" of the result into a 2D array.
Then I will send multiple requests to get json files of each "name" and "id" pairs.
Finally, I will store the event detail into database. (one event per row) But now my code will terminate before it downloaded the json files.
Code:
function newLst(results) {
var event = Parse.Object.extend("event");
for (var i = 0; i < results.length; i++){
Parse.Cloud.httpRequest({
url: 'https://api.example.com/events/'+ results[i].name +'/'+ results[i].id +'.json',
success: function(newLst) {
var newJson = JSON.parse(newLst.text);
var newEvent = new event();
newEvent.set("eventId",newJson.data.id);
newEvent.set("eventName",newJson.data.title);
newEvent.save(null, {
success: function(newEvent) {
alert('New object created with objectId: ' + newEvent.id);
},
error: function(newEvent, error) {
alert('Failed to create new object, with error code: ' + error.message);
}
});
},
error: function(newLst) {
}
});
}
};
Parse.Cloud.job("getevent", function(request, status) {
var event = Parse.Object.extend("event");
var query = new Parse.Query(event);
query.notEqualTo("objectId", "lol");
query.limit(1000);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var myObject = results[i];
myObject.destroy({
success: function(myObject) {
},
error: function(myObject, error) {
}
});
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
var params = { url: 'https://api.example.com/events.json'};
Parse.Cloud.httpRequest(params).then(function(httpResponse) {
var results = [];
var jsonobj = JSON.parse(httpResponse.text);
for (var i = 0; i < jsonobj.data.length; i++) {
var tmp2D = {"name":"id"}
tmp2D.name = [jsonobj.data[i].name];
tmp2D.id = [jsonobj.data[i].id];
results.push(tmp2D);
}
newLst(results);
}).then(function() {
status.success("run job");
}, function(error) {
status.error(error);
});
});
I think my original answer is correct as a standalone. Rather than make it unreadable with the additional code, here it is made very specific to your edit.
The key is to eliminate passed callback functions. Everything below uses promises. Another key idea is decompose the activities into logical chunks.
A couple of caveats: (1) There's a lot of code there, and the chances that either your code is mistaken or mine is are still high, but this should communicate the gist of a better design. (2) We're doing enough work in these functions that we might bump into a parse-imposed timeout. Start out by testing all this with small counts.
Start with your question about destroying all instances of class...
// return a promise to destroy all instances of the "event" class
function destroyEvents() {
// is your event class really named with lowercase? uppercase is conventional
var query = new Parse.Query("event");
query.notEqualTo("objectId", "lol"); // doing this because the OP code did it. not sure why
query.limit(1000);
return query.find().then(function(results) {
return Parse.Object.destroyAll(results);
});
}
Next, get remote events and format them as simple JSON. See the comment. I'm pretty sure your idea of a "2D array" was ill-advised, but I may be misunderstanding your data...
// return a promise to fetch remote events and format them as an array of objects
//
// note - this differs from the OP data. this will evaluate to:
// [ { "name":"someName0", id:"someId0" }, { "name":"someName1", id:"someId1" }, ...]
//
// original code was producing:
// [ { "name":["someName0"], id:["someId0"] }, { "name":["someName1"], id:["someId1"] }, ...]
//
function fetchRemoteEvents() {
var params = { url: 'https://api.example.com/events.json'};
return Parse.Cloud.httpRequest(params).then(function(httpResponse) {
var results = [];
var remoteEvents = JSON.parse(httpResponse.text).data;
for (var i = 0; i < remoteEvents.length; i++) {
var remoteEvent = { "name": remoteEvents[i].name, "id": remoteEvents[i].id };
results.push(remoteEvent);
}
return results;
});
}
Please double check all of my work above regarding the format (e.g. response.text, JSON.parse().data, etc).
Its too easy to get confused when you mix callbacks and promises, and even worse when you're generating promises in a loop. Here again, we break out a simple operation, to create a single parse.com object based on one of the single remote events we got in the function above...
// return a promise to create a new native event based on a remoteEvent
function nativeEventFromRemoteEvent(remoteEvent) {
var url = 'https://api.example.com/events/'+ remoteEvent.name +'/'+ remoteEvent.id +'.json';
return Parse.Cloud.httpRequest({ url:url }).then(function(response) {
var eventDetail = JSON.parse(response.text).data;
var Event = Parse.Object.extend("event");
var event = new Event();
event.set("eventId", eventDetail.id);
event.set("eventName", eventDetail.title);
return event.save();
});
}
Finally, we can bring it together in a job that is simple to read, certain to do things in the desired order, and certain to call success() when (and only when) it finishes successfully...
// the parse job removes all events, fetches remote data that describe events
// then builds events from those descriptions
Parse.Cloud.job("getevent", function(request, status) {
destroyEvents().then(function() {
return fetchRemoteEvents();
}).then(function(remoteEvents) {
var newEventPromises = [];
for (var i = 0; i < remoteEvents.length; i++) {
var remoteEvent = remoteEvents[i];
newEventPromises.push(nativeEventFromRemoteEvent(remoteEvent));
}
return Parse.Promise.when(newEventPromises);
}).then(function() {
status.success("run job");
}, function(error) {
status.error(error);
});
});
The posted code does just one http request so there's no need for an array of promises or the invocation of Promise.when(). The rest of what might be happening is obscured by mixing the callback parameters to httpRequest with the promises and the assignment inside the push.
Here's a clarified rewrite:
Parse.Cloud.job("getevent", function(request, status) {
var promises = [];
var params = { url: 'https://api.example.com'};
Parse.Cloud.httpRequest(params).then(function(httpResponse) {
var results = [];
var jsonobj = JSON.parse(httpResponse.text);
for (var i = 0; i < jsonobj.data.length; i++) {
// some code
}
}).then(function() {
status.success("run job");
}, function(error) {
status.error(error);
});
});
But there's a very strong caveat here: this works only if ("// some code") that appears in your original post doesn't itself try to do any asynch work, database or otherwise.
Lets say you do need to do asynch work in that loop. Move that work to a promise-returning function collect those in an array, and then use Promise.when(). e.g....
// return a promise to look up some object, change it and save it...
function findChangeSave(someJSON) {
var query = new Parse.Query("SomeClass");
query.equalTo("someAttribute", someJSON.lookupAttribute);
return query.first().then(function(object) {
object.set("someOtherAttribute", someJSON.otherAttribute);
return object.save();
});
}
Then, in your loop...
var jsonobj = JSON.parse(httpResponse.text);
var promises = [];
for (var i = 0; i < jsonobj.data.length; i++) {
// some code, which is really:
var someJSON = jsonobj.data[i];
promises.push(findChangeSave(someJSON));
}
return Parse.Promise.when(promises);

Post more JSON on a backbone.js save

I'm using backbone to make a simple POST to my API. However, I need to add additional details to the json post on save about my user. What is the best way and how?
user : {pk:1, name:test}
var ParticipantView = Backbone.View.extend({
el: '#participant-panel',
events: {
'submit #participant-form': 'saveParticipant'
},// end of events
saveParticipant: function (ev) {
var participantDetails = $(ev.currentTarget).serializeObject();
var participant = new Participant();
participant.save(participantDetails, {
success: function (participant) {
alert("created")
},
error: function (model, response) {
console.log('error', model, response);
}
});// end of participant save function
return false; // make sure form does not submit
}// end of save participants
});// end of participant view
just add it to your participantDetails variable like this:
var participantDetails = $(ev.currentTarget).serializeObject();
var userinfo = {pk: 1, name: "test"};
participantDetails.user = userinfo;
If you want to add properties to the main object do:
var participantDetails = $(ev.currentTarget).serializeObject();
participantDetails.pk = 1;
participantDetails.name = "test";

Backbone Collection not being included in JSON string when using JSON.stringify on model

I am having an issue where my collection property (in this case Parameters Collection) in my model is not being included in the JSON string created by the JSON.stringify function. Is there any reason why this might be happening? It basically just excludes it and adds the rest of the variables to the JSON string.
Here is the event:
EventAggregator.on('toggleFacet', function (facets) {
var facets = SearchOptionsUtil.getCheckedFacets(facets);
var sortOptions = SearchOptionsUtil.getSortOptions();
var searchOptions = new SearchOptionsModel();
for(var facet in facets){
var id = facet;
var value = facets[facet];
searchOptions.parameters.add(new ParameterModel({id: id, values: value.split(',')}));
}
var criteria = $.extend(facets, sortOptions);
location.hash = UriUtil.getUriHash(criteria);
RequestUtil.requestSearchResults(searchOptions);
});
Here is the fetch:
requestSearchResults: function (searchOptions) {
//fetch the results
var performSearchModel = new PerformSearchModel();
var searchOptionsJson = JSON.stringify(searchOptions);
performSearchModel.fetch({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({searchOptionsJson: searchOptionsJson}),
success: function (response) {
console.log("Inside success");
console.log(response);
},
error: function (errorResponse) {
console.log("Inside Failure")
console.log(errorResponse.responseText)
}
}) //have to wait for the fetch to complete
.complete(function () {
//show our regions
App.facetsRegion.show(new FacetListView({collection: performSearchModel.facets}));
App.resultsRegion.show(new ResultListView({collection: performSearchModel.results}));
//perform search fetch complete
});
}
and here is the model:
var SearchOptionsModel = Backbone.Model.extend({
defaults: {
parameters: ParameterCollection,
currentItemId: '{EE8AA76E-0A3E-437B-84D8-AD7FCBAF2928}',
sortBy: 0,
sortDirection: 'asc',
resultsPerPage: 10
},
initialize: function () {
this.parameters = new ParameterCollection();
//fetch calls an on change event.
this.on("change", this.fetchCollections);
},
url: function () {
return '/Services/Search/SearchService.asmx/SearchOptions';
},
parse: function (response) {
var data = JSON.parse(response.d);
return data;
},
fetchCollections: function () {
//when we call fetch for the model we want to fill its collections
this.parameters.set(
_(this.get("parameters")).map(function (parameter) {
return new ParameterModel(parameter);
})
);
}
});
UPDATE**
So I changed the way I create and add the parameters collection in the SearchOptionsModel and the JSON object is being formed correctly. I changed it from this:
var searchOptions = new SearchOptionsModel();
for(var facet in facets){
var id = facet;
var value = facets[facet];
searchOptions.parameters.add(new ParameterModel({id: id, values: value.split(',')}));
}
To this:
var parameters = new ParameterCollection();
//loop through all of the variables in this object
for(var facet in facets){
var id = facet;
var value = facets[facet];
parameters.add(new ParameterModel({id: id, values: value.split(',')}));
}
var searchOptions = new SearchOptionsModel({parameters: parameters});
Now the parameters are filled under the attributes in the model and I see an empty parameters variable on the searchOptions object (which was being filled before instead). Why is there a parameters variable set in the SearchOptionsModel if I am not explicitly creating it? Is it because the parameters default is set to a collection?
To convert a Backbone model to JSON, you must use the toJSON method:
model.toJSON();
Check doc here: http://backbonejs.org/#Model-toJSON

How do I loop through a json collection of strings with Mustache?

The MVC that creates the array of strings is
public JsonResult GetInvalidFilesAJAX(JQueryDataTableParamModel param)
{
string[] invalidFiles = new string[] { "one.xls", "two.xls", "three.xls" };
return Json(new
{
Status = "OK",
InvalidFiles = invalidFiles
});
}
And the javascript that should loop through and print out each string is
$.ajax(
{
type: 'POST',
url: 'http://localhost:7000/ManualProcess/GetInvalidFilesAJAX',
success: function (response) {
if (response.Status == 'OK') {
//Use template to populate dialog with text of Tasks to validate
var results = {
invalidFiles: response.InvalidFiles,
};
var template = "<b>Invalid Files:</b> {{#invalidFiles}} Filename: {{invalidFiles.value}} <br />{{/invalidFiles}}";
var html = Mustache.to_html(template, results);
$('#divDialogModalErrors').html('ERROR: The following files have been deleted:');
$('#divDialogModalErrorFiles').html(html);
How do I refer to the string in the array? The way above is not correct. All the example I find seem to be for when the Jason collection has property names.. in my case it is just a key value pair (I guess?)
There is no built in way. You must convert the JSON into an array or loop through the data yourself, e.g,
var data = JSON.parse(jsonString); // Assuming JSON.parse is available
var arr = [];
for (var i = 0, value; (value = data[i]); ++i) {
arr.push(value);
}
Alternatively:
var arr = [];
for (var prop in data){
if (data.hasOwnProperty(prop)){
arr.push({
'key' : prop,
'value' : data[prop]
});
}
}
And then to display it:
var template = "{{#arr}}<p>{{value}}</p>{{/arr}}";
var html = Mustache.to_html(template, {arr: arr});
This is assuming your JSON Object is one level deep.

Categories