IkeDoud
IkeDoud

Reputation: 87

.append or .after defined as a variable?

So I'm trying to figure out the best way to get this to work. I have a long list of code that's pulling off of a JSON database, and I'm trying to streamline it. I've created the following function:

var insertData = function(formattedData, originalData, referencePoint, insertPoint, insertStyle) {
  var formattedData = originalData.replace("%data%", referencePoint);
  $(insertPoint).insertStyle(formattedData);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

Is it possible to define a dot function similar to how I have it here - referenced as one of the function's variables? This current code says that insertStyle is not a function - how do I get the code to recognize that insertStyle should be taking a variable name? As in, if my fifth variable called by insertData is append, it should be read as .append.

As a reference, here's how I'm calling the function:

insertData("formattedHeaderName", "HTMLheaderName", bio.name, "#header", "prepend");

Thanks for any assistance or thoughts in advance!

Upvotes: 1

Views: 52

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

When you pass an argument to a function, like you do in:

insertData("formattedHeaderName", "HTMLheaderName", bio.name, "#header", "prepend");

Those arguments are strings. Not jQuery methods.

So, a solution would be to define all the methods you need to use...
And just compare the string passed to decide.

var insertData = function(formattedData, originalData, referencePoint, insertPoint, insertStyle) {

  var formattedData = originalData.replace("%data%", referencePoint);

  if(insertStyle=="prepend"){
    $(insertPoint).prepend(formattedData);
  }
  if(insertStyle=="append"){
    $(insertPoint).append(formattedData);
  }
  if(insertStyle=="after"){
    $(insertPoint).after(formattedData);
  }
  // And so on...
}

Maybe there is some other ways to achive this...
But this one is quick and easy to implement.

Upvotes: 0

Platinum Azure
Platinum Azure

Reputation: 46183

You're looking for a computed property:

$(insertPoint)[insertStyle](formattedData);

Basically, every property access can be represented as a computed property:

foo["bar"];  // same as foo.bar

In your original code, you're using a non-computed property so the interpreter looks for a method literally called "insertStyle", which doesn't exist.

Upvotes: 1

Related Questions