Good day! I need to render a model's attributes to JSON so I can pass them into a template.
Model:
var UserInfo = Backbone.Model.extend({
url: appConfig.baseURL + "users/",
});
Template:
<script type="text/html" class="template" id="profile-form">
<h2 class="ui-li-heading"><%= username %></h2>
<p class="ui-li-desc"><strong><%= phone %></strong></p>
</script>
View:
var ProfilePageView = Backbone.View.extend({
events: {
'click #edit': "edit"
},
initialize: function () {
this.template = $.tpl['profile-form'];
var user = new UserInfo()
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
console.log(user) //returns correct object with attrs
console.log(user.toJSON()) //returns empty object
},
render: function (eventName) {
$(this.el).html(this.template());
},
edit: function () {
window.workspace.navigate('#account/edit', { trigger: true});
}
});
When i put in console something like this, user.toJSON() returns correct data
var user = new UserInfo();
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
But when i put it to my view, its returns Object {}.
Where is a mistake or tell me how can differently pass to the template data received from the server in json format? Thanks!
You appear to have two problems. fetch is asyncronous, so you need to use a callback to use the information. But first, an explanation about toJSON. .toJSON() doesn't actually return a JSON string, it returns an object that is what you want JSON to stringify. This allows you to modify the toJSON method to customize what attributes will be taken from your model or collection and added to the JSON string representation of your model. Here is a quotation from the Backbone.js docs:
toJSON collection.toJSON([options])
Return a shallow copy of the model's attributes for JSON
stringification. This can be used for persistence, serialization, or
for augmentation before being sent to the server. The name of this
method is a bit confusing, as it doesn't actually return a JSON string
— but I'm afraid that it's the way that the JavaScript API for
JSON.stringify works.
So you should replace this line in your code
console.log(user.toJSON())
with this one
console.log(JSON.stringify(user))
The object that you saw was returned by toJSON will then be turned into JSON.
Now, even after you do that, it won't work properly, because you will execute the console.log before you get the data for your model from fetch. fetch is asynchronous, so you need to call any code you want to be executed after the fetch is done in the success callback:
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST',
success: function(){
console.log(user);
console.log(JSON.stringify(user));
}
});
Related
When calling JsonRest using dojo, how can I pass parameters with it.
var rest = new JsonRest({
target: "/path/to/service"
});
JsonRest example:
require(["dojo/store/JsonRest"], function(JsonRest){
// create a store with target your service
var store = new JsonRest({
target: "/path/to/service"
});
// make a get request passing some options
store.query("foo=bar", {
start: 5,
count: 5,
sort: [
{ attribute: "color", descending: true }
]
}).then(function(results){
// result here
});
});
The function to use in your case is query with signature query(query, options)
When called, query will trigger a GET request to {target}?{query}, as described in dojo docs.
Please keep in mind that:
If query is an object, it will be serialized.
If query is a string, it is appended to the URL as-is.
If options includes a sort property, it will be serialized as a query parameter as well;
Your service/API should:
Return a array of objects in JSON format.
Return an empty array if no match is found.
I am trying to pass a simple variable value into an HTML file using ember.js. My value is contained within a json file called value.json.
My HTML code is as follows:
<h1>I won {{App.moneyvalue}} today!</h1>
However when I pass the json call via ember, it think that the entire call is a variable:
App = Ember.Application.create({
moneyvalue: function () {
return $.getJSON( "js/value.json", function( data ) {
return data.tot;
});
}
}
And returns the following:
I won function () { return $.getJSON( "js/donors.json", function( data ) { return data.tot; }); } today!
As it seems to think that moneyvalue is a string variable as opposed to a value?
The jSON file is superbasic
{
"tot": 100
}
Where is this going wrong?
you're supplying Handlebars with a function, generally you would use a computed or normal property on the object. In this case you really just shouldn't define it in the application scope either, I'd recommend using an application route (it's the root route of your app).
App.ApplicationRoute = Ember.Route.extend({
model: function(){
return $.getJSON( "js/value.json");
}
});
Then in your handlebars just use
<h1>I won {{tot}} today!</h1>
Here's an example: http://emberjs.jsbin.com/OxIDiVU/576/edit
I am new to Backbones.js, and I was trying to get my JSON urls and parse them correctly.
This is my code:
window.Post = Backbone.Model.extend({
initialize: function(options) {
this.id = options.id;
},
url: function() {
return 'api/get_post/?post_type=movies&id=' + this.id;
},
parse : function(response) {
return response.posts;
},
});
window.Posts = Backbone.Collection.extend({
model: Post,
defaults: {
model: Post,
},
url: "api/get_recent_posts/?post_type=movies",
parse : function(response) {
return response.posts;
},
});
It seems that parsing for both overrides each other or something. when I remove the parse option from the Post class, I get a full response from the collection, but not from the model.
Are there any clear examples on how to set parsing for different son hierarchies? my JSON result have a status ok before it dives into the actual data.
I've never used bones.js but maybe these examples will help.
I think what you want to do is get rid of the parse() function in your collection. This assumes that since it is a Post collection, your data will come in as an array of Post JSON objects [{id:'1', 'sub':{data}},{id:'2', 'sub':{data}},{id:'3', 'sub':{data}}] or something like that.
If your Post model has sub-models or collections, your model parse() will then take the sub-object property name and do something with it.
// In Post Model definition
parse:function(response) {
if (response.sub) {
// create some model or collection etc.
}
}
You might have to pass an option parse:true when you do your collection fetch.
I posted something along these lines which might help you see how sub-models can be instantiated on fetch calls.
Backbone.js: Load multiple collections with one request
Cast/initialize submodels of a Backbone Model
I hope this helps.
I can successfully make a jQuery Ajax call into my C# Controller and receive back an XML string, but I need to in turn gather some Portfolio dates and package them up into a JSON object so I can send them back into another C# Controller.
If it's a C# issue, then I apologize if I'm in the wrong forum...however I'd like to pass my JSON object into the server side controller ..
Here's what I'm trying to do:
var nodeDatesJson = {"nodedates": // CREATE JSON OBJECT OF DATE STRINGS
{ "date": 01/20/2012,
"date": "01/21/2012" } };
getTradeContribs(thisPfId, nodeDatesJson.nodedates.date);
Now call the next js function:
function getTradeContribs(pfid, nodedates) {
//alert(nodedates);
$.ajax({ // GET TRADE CONTRIBS FROM SERVER !!
url: "/Portfolios/getTradeContribs?portfolioId=" + pfid + "&nodedates=" + nodedates,
type: "GET", // or "PUT"
dataType: "json",
async: true,
success: parseTradeContribs,
error: function (error) {
alert("failed in opening Trade Contribs file !!!");
}
});
}
function parseTradeContribs(data) {
alert("In parseTradeContribs..." );
$(data).find("Trade").each(function(){
$(".TradeContrib").append($(this).text());
})
}
and my C# controller is trying to read in the "nodedates" JSON object, but HOW do I read it in ?
public string getTradeContribs(string portfolioId, **string nodedates**)
{
// Build Portfolio Select request here !
RequestBuilder rzrRequest = new RequestBuilder();
// REQUEST FOR CONTRIBUTIONS !
// ... more code here..
xmlResponse.LoadXml(contribResponse);
string jsonTest = #" {""nodedates"": ""date"":""01/01/2012""}";
//return xmlResponse.OuterXml; // WORKS FINE
return "<Trade><TradeId>1234</TradeId></Trade>"; // RETURN TEST XML STR
}
thank you in advance...
Bob
The best way to receive a list of dates in a MVC action is to bind to a collection. What this means is that you should put your dates and other attributes in a form with the following naming convention:
<input type="hidden" name="dates" value="2012-1-20" />
<input type="hidden" name="dates" value="2012-1-21" />
Then you should serialize this form (look into jquery's docs for this) and post its data to your action, which will be something along the lines of:
public ActionResult getTradeContribs(string portfolioId, IList<DateTime> dates) {
// Do your work here
}
You should really take a look into MVC Model binding and collection binding as well:
Model binding to a list
Model binding objects
Also, if I may, your javascript object has two properties with the same name, which is probably not what you mean. If you want to have multiple dates stored somewhere in a object, you should use an array:
var nodeDatesJson = {"nodedates":
[ "01/20/2012", "01/21/2012" ] };
Sorry, but I didn't understand your doubt very well...but here it goes:
Maybe you should pass the json, well-formatted, as a string and use some C# parser.
This way you can get a object in server-side as same as the Json object in javascript.
=]
I am new to dojo and spring development. I am trying to populate a Tree widget using a json response from a spring-mvc controller. I'm following the examples from the dojocampus website quite closely.
Firstly if I use a local data source it works ok:
<script type="text/javascript">
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.Tree");
dojo.addOnLoad(function() {
var rawdata = [{"rid":"b1c","name":"Test Parent","children":[{"rid":"1c4","name":"Test Child 1","children":[]},{"rid":"ee6","name":"Test Child 2","children":[]}]}];
var store = new dojo.data.ItemFileReadStore({
data: {
identifier: 'rid',
label: 'name',
items: rawdata
}
});
var treeModel = new dijit.tree.TreeStoreModel({
store: store,
query: {name: 'Test Parent'},
childrenAttrs: ["children"]
});
new dijit.Tree({
model: treeModel
},
"treeOne");
});
</script>
<div id="treeOne">
</div>
But if I use my json url the tree doesn't appear:
<script type="text/javascript">
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.Tree");
dojo.addOnLoad(function() {
var store = new dojo.data.ItemFileReadStore({
url: "/Demo2/glossaryobjects/categories.json"
});
var treeModel = new dijit.tree.TreeStoreModel({
store: store,
query: {name: 'Test Parent'},
childrenAttrs: ["children"]
});
new dijit.Tree({
model: treeModel
},
"treeOne");
});
</script>
<div id="treeOne">
</div>
When I debug with Firebug I can see that the json response appears to be loaded correctly. It looks like this:
{"identifier":"rid","items":{"rid":"b1c","name":"Test Parent",
"children":[{"rid":"1c4","name":"Test Child 1","children":[]},
{"rid":"ee6","name":"Test Child 2","children":[]}]}, "label":"name"}
There is an error in Firebug:
"dijit.tree.TreeStoreModel: query {"name":"Test Parent"} returned 0 items, but must return exactly one item"
It looks like the ItemFileReadStore is not correctly loaded. Anyone know what I'm doing wrong? I've been tearing my hair out for days trying to get this to work, so any help is much appreciated.
Cheers,
Rod.
OK! Problem solved (for me):
If you have a close look at the store produced by each, the data is there for both, but the way the store represents each is different.
With the url JSON data, you get
_arrayofallitems []
_arrayoftoplevelitems Object {....
id...
items...
etc.
with the string data, you get
_arrayofallitems [] 62 items
_arrayoftoplevelitems
[0]
id
items
etc.
If you intercept the JSON response from xhrGet, and compare it to the string, you'll see that the JSON response is not an array (no []) whereas the string is.
Solution: declare an empty array, push the JSON response into it,
then pass the array to ItemFileReadStore:
dojo.xhrGet( {
url: 'test.php',
handleAs: "json",
preventCache: 'true',
load: function(response, ioArgs){
var rawdata = [];
rawdata.push(response);
var store = new dojo.data.ItemFileReadStore({ data: {
identifier: "id",
label: "label",
items: rawdata }
});
loadtree(store);
}});
It worked for me (finished an afternoon of frustration)...
The error you mentioned:
"dijit.tree.TreeStoreModel: query {"name":"Test Parent"} returned 0 items, but must return exactly one item"
Should be from using a TreeStoreModel instead of a ForestStoreModel. The former requires only one item be returned for the root node. Your fix probably worked because you shoved it into a single array.
Take a look at:
http://ofps.oreilly.com/titles/9780596516482/application_widgets.html