How to create list of object in jquery ?
Example:
Object name: rowdataObject having properties.
NOw, i want to create list of rowdataObject and pass to MVC.
Please suggest me how to create list of object in javascript and pass as argument in controller.
Thanks
<html>
<head>
<script type="text/javascript">
$(function() { // this is jQuery's version of `document.onload = function` which basically means, "start doing this when page is loaded"
// an Object in jQuery is extremely simple in nature
var obj = {}; // this is officially an object
// add to the object by simply creating properties
obj.prop1 = "This property is a string";
// add inner objects just as easy
obj.class1 = { prop1: "This inner object now has it's own property" }
// to pass this to a "controller" in jQuery, you will use a form of $.ajax
$.ajax({ // here you start creating ajax options
type: 'POST', // makes this retrievable via POST on server side, exp: $_POST['keyName']
data: JSON.stringify({ keyName: obj }), // easiest way to send data as key|value
url: 'http://www.example.com' // here you need the url to your controller
}) // now, use jQuery chainability to see results returned from controller
.done(function( data, textStatus, jqXHR ) {
// this function will fire only if the controller makes a successful return
/* do work, exp: */
console.log(data); // this would show the results of what the controller returned in your browser's developer console
})
})
</script>
</head>
<body>
References
JS Object
$.ajax
jQuery's Chainability
JSON
Related
How to fetch console.log data in another function .we are getting value in console for example
triggerBtm: function(btmEvtObj){
$(document).trigger(btmEvtObj);
console.log(btmEvtObj);
},
Need to fetch value of "btmEvtObj" in another function in separate file. I need to fetch value in another function placed in separate file.
Why don't you just store that value in a variable. All javascript variables declared outside of a scope are global, so they can be accessed from any function.
var eventObjectFromTrigger;
triggerBtm: function(btmEvtObj){
$(document).trigger(btmEvtObj);
eventObject = btmEvtObj;
},
Then in your other function (whether its a separate file or not), just access it...
function foo(){
$(eventObjectFromTrigger).doSomething();
}
by the syntax it looks like triggerBtm is a method contained by another object. Add a return to the method body and access it in another file by calling the method from the object.
File 1
var yourObject = {
triggerBtm: function(btmEvtObj){
$(document).trigger(btmEvtObj);
console.log(btmEvtObj);
return btmEvtObj;
},
};
File 2
var yourValue = yourObject.triggerBtm();
Try Replacing The Whole Console with user-defined function:
var console = {log: function(data){
$("#console-1").append(JSON.stringify(data)+"\n");
},
error: function(data){
$("#console-1").append(JSON.stringify(data)+"\n");
},
warn: function(data){
$("#console-1").append(JSON.stringify(data)+"\n");
}};
This example will append all console log data in div#console-1.
I have a JSON response like this:
google.friendconnect.container["renderOpenSocialGadget"](
{
height: 200,
url: "http://username.github.io/",
"view-params": {"style":"light","url":"https://www.facebook.com/username","height":"258"},
"prefs": {"style":"light","url":"https://www.facebook.com/username","height":"258"}
}, skin);
I want to reach the values such as height, url, view-params but couldn't.
I tried this but it didn't worked:
console.log(google.friendconnect.container["renderOpenSocialGadget"].url);
The expression google.friendconnect.container["renderOpenSocialGadget"]( is equivalent to google.friendconnect.container.renderOpenSocialGadget(
Given that, we see that this is a method of an object, getting a JSON object and an additional parameter (skin) as parameters.
As the object is somehow "anonymous" parsed directly in to the function call, you can't access it anymore, once the function has consumed it.
Check, if google.friendconnect.container has getter methods (they usually have ...) by console.log(google.friendconnect.container).
EDIT
Just an Idea: you might catch the call and pass it over:
google.friendconnect.container["MyrenderOpenSocialGadget"] =
google.friendconnect.container["renderOpenSocialGadget"];
google.friendconnect.container["renderOpenSocialGadget"] = function(obj, skin) {
// do what you want with obj
console.log(obj.url);
//call original
google.friendconnect.container["MyrenderOpenSocialGadget"](obj, skin);
});
<!DOCTYPE HTML>
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>
</head>
<body>
<script>
var mod=Backbone.Model.extend({});
var col=Backbone.Collection.extend({model:mod, url: 'test.php'});
col.fetch();
</script>
</body>
</html>
If run this primitive code in Firefox, Firebug gives me the following error:
TypeError: col.fetch is not a function
col.fetch();
Why is that? I can't see no error or typo... Thanks.
You have few mistakes in your code:
You need to specify model and collection:
var Mod = Backbone.Model.extend({});
var Col = Backbone.Collection.extend({model: Mod, url: 'test.php'});
Create instance of collection with specified model:
var collectionInstance = new Col({model: new Mod()});
Fetch collection:
collectionInstance.fetch();
For more details, please, see Backbone docs.
If you are not familiar with a Class/Constructor/Prototype vs Instance here is an explanation:
Say we have a forum where every user has some posts. We want to represent the Posts a user has in a Collection called "Posts". Now here's the thing, you can can have multiple users, therefore you will need multiple instances of the collection (which is basically an array with some super-cool features that Backbone provides and you specify). We want to create a "blueprint" for how this array works and the cool things it can do (because we don't want to rewrite the functionality for every single array we create). A Class/Constructor/Prototype is that blueprint.
//Post is a Model Class/Constructor/Prototype. We can make multiple "instances" of Post.
var Post = Backbone.Model.extend({
starPost: function() {
//contains code to "star" a post
},
pinPost: function(){
//contains code to "pin" the post
},
//some other cool functions to do cool things to a post
});
//Posts is the Collection Class/Constructor/Prototype. We can make multiple "instances" of Posts for each User.
var Posts = Backbone.Collection.extend({
url: function() {
return '/api/posts/' + this.options.userID
},
model: Post,
findStarredPosts: function(){
//has code to return all Post models that are "starred"
},
findPinnedPosts: function(){
//has code to return all Post models that are "pinned"
}
});
//please note that the FIRST ARGUMENT is an empty array (meaning we are starting this collection with no models inside). the SECOND ARGUMENT is the options (which will be saved into the instances `this.options`). `options` is what makes this instance unique when going to the server. You need to write in your `url` function HOW you're going to use what you passed in `options` to communicate with the server
var user1Posts = new Posts([], {
userID: 123 //this is an option passed in which is specific to this INSTANCE. It will get read by the `url` function and generate an instance of this posts collection Specific to user1
});
var user2Posts = new Posts([], {
userID: 456 //this is an option passed in which is specific to this INSTANCE. It will get read by the `url` function and generate an instance of this posts collection Specific to user2
});
//this command actually tells Backbone to go our and request user1's posts from the server and put them into the `user1Posts` collection.
user1Posts.fetch();
Point being, you NEVER run functions on Constructors/Prototypes/Classes. You only act on their instances. The only thing you can do is create instances of those Constructors/Prototypes/Classes.
I hope this makes some sense. If not I can (and will) clarify.
I have a problem with implementing a javascript class whose constructor is populated by an ajax call. The data is read from a file and populates correctly the class properties in an asynchroneous manner. The following code works alright:
function Pattern(file){
this.pattern = new Array();
$.ajax({
type: 'GET',
url: file,
dataType: 'text',
context: this,
success: function (data){
...
this.buildPattern(data);
},
error: function (jqXHR, textStatus, errorThrown){
alert('Problem loading file \'' + file + '\'');
}
});
}
Pattern.prototype.buildPattern = function(pattern){
do{
...
this.pattern[i][j] = pattern[i][j];
...
}while(pattern[k] != '!');
}
The problem happens when I access another method after instancing the class:
Pattern.prototype.getPattern = function(number){
...
return this.pattern;
}
Using this code:
var pattern1 = new Pattern('filename.ext');
var myPattern1 = pattern1.getPattern(1);
Due to the asynchronous way of initializing my properties in the class, calling the method getPattern() just after class creation returns an empty result as this.pattern has not yet completed loading and post-processing.
I know there exist jQuery objects Deferred and Promise but I haven't found any implementation of them using javascript and classes.
Can anyone point me in the right direction?
Sorry to write this as answer and not as comment my tablet wouldn't let me write comments at the moment.
I just thought you might trigger an event (maybe use PubSub) and put the code that uses the class in a EventHandler-function that is triggered after your class is loaded completely.
Using one of the many options defined at http://api.jquery.com/jQuery.ajax/ (or anywhere else) can I map the incoming data to a specific data type rather than the default generic object that is usually returned?
My usual method is to "convert" the generated object by grabbing each property and placing it into the constructor for the new object that I really want to use. Then, I just forget about the old object. I would imagine that there is a much more efficient way to do this.
I came up with/found a few ideas such as simply adding methods to each of the returned objects. It works well, but I just have to know if there is an even more efficient method.
So you're saying that you have code like the following:
function Pirate(name, hasParrot)
{
this.name = name;
this.hasParrot = hasParrot;
}
and the server is sending this JSON data:
{
name: "Blackbeard",
hasParrot: true
}
which jQuery is converting to a plain object, right?
If that's the case, you can use a custom datatype to parse the server's data directly into a Pirate object, like so:
// First define the converter:
jQuery.ajaxSetup({
converters: {
"json pirate": function(obj) {
if(!obj.name || typeof obj.hasParrot === "undefined")
{
throw "Not a valid Pirate object!";
}
else
{
return new Pirate(obj.name, obj.hasParrot);
}
}
}
}
// Then use it!
$.ajax("http://example.com/getPirate", {
data: {id: 20},
dataType: "pirate",
success: function(pirate){
console.log(pirate instanceof Pirate); // Should be true
}
});
Edit: If you really want to skip the step of converting to JSON, you could could replace "json pirate" above with "text pirate" and write your own parser for the raw text returned by the ajax call.