0

I need to acomplish something like following...

My html would be

<div id="targetdiv">
<div class="Comments30" title="{@something1}"></div>
<div class="{@something2}" title="{@something3}"></div>
<div class="Comments30" title="{@something4}"></div>
</div>

My json would be

var myJson=
{
something1 : value1
something2 : value2
something3 : value3
something4 : value4
}

and i want to bind them using jquery like

$('#targetdiv').bindMyJSON(myJson);

How can I acheive this. I know it would be something like

jQuery.fn.extend({
bindMyJSON : function(json){    

}})
2

3 Answers 3

0

You may do this with some $.fn.renderMyJSON(), but there is a reason template engines like _.template, handlebars etc. exist.

I made a little fiddle with some basic renderByJson() plugin using .replace(), but keep in mind that this only replaces the first found occurance of the string to replace: http://jsfiddle.net/6dece/

Basic code looks like this:

jQuery(function($) {
    $.fn.renderMyJSON = function(json) {
        var $el = $(this);

        $.each(json, function(key, val) {
            $el.html($el.html().replace('{@' + key + '}', val));
        });
    };


    var json = $.parseJSON('{"something1" : "value1","something2" : "value2","something3" : "value3","something4" : "value4"}');

    $('#targetdiv').renderMyJSON(json);
})
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer... this worked for me, i just added var regex = new RegExp("{@" + key + "}", "g"); for global replace. Thank you so much.
this is awsome...but how can i get the changed values from html into my JSON object? is there any generic way to do this?
Yeah, using a RegEx for replacing solves the "first match-only" problem. My function only handles rendering the JSON (thus I named it renderMyJSON), if you need real data-binding (I guess you even want bi-directional data-binding), you have to write a lot more stuff. Maybe you're interested in AngularJS and its way of handling bi-directional data-binding (see first example here: angularjs.org). If you want to write it on your own, you have to 1. collect the information from the DOM via jQuery (maybe use data-attributes) 2. use JSON.stringify() to build a JSON 3. overwrite your JSON
0

Underscore.js has a great _.template function that I would recommend using but here is one way you could solve it below:

makeTemplate is a function that generate a function that interpolates your variables. You can pass it a template string and it will generate a function that when called with an object will interpolate the properties. Processing the template first is generally more efficient than finding and replacing each time.

var makeTemplate = (function() {
  var escapeMap = {
    '\n'      : '\\n', 
    '\"'      : '\\\"',
    '\u2028'  : '\\u2028',  // line separator
    '\u2029'  : '\\u2029'   // paragraph separator
  };

  return function (templateString) {
    // Escape Special Characters
    templateString = templateString.replace(/["\n\r\u2028\u2029]/g, function(index) {
      return escapeMap[index];
    });

    // Replace interpolation ({@foo}) variables with their object counterpart.
    templateString = templateString.replace(/\{@(\w+)\}/g, '" + (obj["$1"] || "") + "');

    // Return template function.
    return new Function('obj', 'return "' + templateString + '";');
  };
}());

Once you have your makeTemplate function you can define your html and make your template function:

var html = '<div id="targetdiv"><div class="Comments30" title="{@something1}"></div><div class="{@something2}" title="{@something3}"></div><div class="Comments30" title="{@something4}"></div></div>';

var template = makeTemplate(html);

Once you have your template function you can call the template function:

var interpolatedHtml = template({
  something1 : "value1",
  something2 : "value2",
  something3 : "value3",
  something4 : "value4"
});

1 Comment

can you please explain what this line will do??? (templateString = templateString.replace(/\{@(\w+)\}/g, '" + (obj["$1"] || "") + "');) and what will be the benefit of doing this? Thank u
0

what i would do is assign the key names of myJson to the div elements as class attributes and iterate over the targetDiv collection assigning the corresponding values to the elements assuming that the class names are static and unique

html

<div id="targetDiv">
    <div class="something1"></div>
    <div class="something2"></div>
    <div class="something3"></div>
</div>

js

var container = $("#targetDiv");
$.each(myJson, function(key, value)
{
  container.filter("." + key).attr("title", value);
});

2 Comments

this is a good option but I was looking for something which can help me changing any attribute I want , like style or class or text or any attribute. Thank you so much. the same kind of solution I saw in Jquery.applyJSON
you can replace and / or add more attributes in a similar fashion just duplicate this line and change the attribute name but you cannot change the class name of course because its your point of reference if you want to store more info use data- attributes html5doctor.com/html5-custom-data-attributes. this solution is pure jquery no frameworks or templating libs were used while creating this snippet :P

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.