I have a namespace called "X" and it has a getJSON function that fetches some file from the server. I want to reuse this namespace with varying contents. Here is the code:
var uid = "27D76901-B6B1-B332-918B-D9F5A7152EFC";
var X = {
el: "",
elMarkup: "",
url: "",
initialize: function(el, elMarkup, url){
$.getJSON(url, function(data){
el.find("p").remove().end();
$.each(data.comments, function(key, value){
el.append(elMarkup);
})
})
}
};
X.el = $("#comments");
X.elMarkup = "<p>"+ value.content +" by "+ value.user +"</p>";
X.url = "http://example.com/getComments?uid=" + uid;
X.initialize(X.el, X.elMarkup, X.url);
I am having a problem with the elMarkup variable for the $.each loop. How can I define this variable dynamically? Thanks!
You could try this:
X.elMarkup = function(value) {
return "<p>"+ value.content +" by "+ value.user +"</p>";
};
And then in your $.getJSON() callback:
$.each(data.comments, function(key, value){
el.append(elMarkup(value));
});
That is, instead of defining X.elMarkup as a string, define it as a callback function that generates the particular html structure you need. Then your generic initialize() function just has to call elMarkup() and pass the current value that needs formatting.
Note that it doesn't really make sense to set the properties as X.el = ... if you're just going to pass those properties as arguments to the X.initialize() function. It would make more sense to just pass the required values directly and have X.initialize() save the values as properties if needed. Or set the properties and call X.initialize() with no arguments.
Change the following:
$.each(data.comments, function(key, value){
el.append(elMarkup);
})
to
$.each(data.comments, function(key, value){
el.append($('<p />', {"html": value.content + " by " + value.user}));
})
because of the reason I mentioned in comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With