3

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!

3
  • X.elMarkup = "<p>"+ value.content +" by "+ value.user +"</p>"; will give you undefined for both variables as they are not defined outside the function. Commented May 20, 2013 at 9:38
  • @nnnnnn If I am going to define the value variables inside the loop, then I will not be able to reuse the namespace. Other json results does not contain the same array. I need the loop to accept varying value variables. Commented May 20, 2013 at 9:40
  • Yes, I realised just after posting the comment. Sorry. Commented May 20, 2013 at 9:41

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.