Advertisements
jump to navigation

jsRazor – New Way of Rendering Json That Is Pure Genius May 9, 2013

Posted by ActiveEngine Sensei in ActiveEngine, Ajax, jQuery, JSON.Net, KnockoutJS, Open Source, Problem Solving.
Tags: , , , , ,
add a comment

DClick this link immediately, and you’ll see wonderful things! Sensei has said many times that simple is better, and rgubarenko of MakeItSoft has a brand spanking new template engine that is so simple it makes you speechless.  His premise:  every possible rendering task can be accomplished as a random combination of two functional primitives:

repeat – repeats fragment of HTML code for each object in array
toggle – shows or hides fragment of HTML depending on boolean flag

Here is an example taken from the github site.  To get the output display below:

jsRazor Example Output

from a Json data set that looks like this:

var data_Themes = [ { name: "Dreaming Theme", colors: ["#2A1910", "#9E7064", "#B0967C", "#E7435E", "#6D4F3F"] },

{ name: "Moth Theme", colors: ["#30382D", "#565539", "#78765F", "#403F2B"] },

{ name: "5 Dark Theme", colors: ["#000000", "#280705", "#2E0500", "#3B0000", "#3C1100"] },

{ name: "Blue Volcano Theme", colors: ["#5077FF", "#8A84FF", "#81C1FF"] } ];

You will have a template that looks like this:

<pre><div id="example">
  <ul>
    <!--repeatfrom:themes-->
    <li> 
      <div class="name">{name} ({CountColors} colors)</div>
      <!--repeatfrom:colors-->
      <div class="wrap">
        <div class="color" style="background-color:{item};">
          <!--showfrom:dark-->
          <span style="color:white">{item}</span>
          <!--showstop:dark-->
          <!--showfrom:light-->
          <span style="color:black">{item}</span>
          <!--showstop:light-->
        </div>
        <div class="rgb">({R},{G},{B})</div>
      </div>
      <!--repeatstop:colors-->
    </li>  
    <!--repeatstop:themes-->
  </ul>
</div></pre>

The controller that creates the final result is as follows:

<pre>// get initial template
var tmp = document.getElementById("example").innerHTML; 
// repeat theme objects (pass array of themes to repeat functional)
tmp = $.jsrazor.repeat(tmp, "themes", data_Themes, function (tmp, idx, item)
{
  // repeat inner color objects (pass array of colors of the current theme item)
  tmp = $.jsrazor.repeat(tmp, "colors", item.colors, function (tmp, idx, item)
  {
    // use toggle to show dark or light color text (to be contrast with background)
    tmp = $.jsrazor.toggle(tmp, "dark", hex2rgb(item).mid <= 128);
    tmp = $.jsrazor.toggle(tmp, "light", hex2rgb(item).mid > 128);
    // output RGB representation of the color as custom value
    tmp = tmp
      .replace("{R}", hex2rgb(item).r)  // red
      .replace("{G}", hex2rgb(item).g)  // green
      .replace("{B}", hex2rgb(item).b); // blue
    // return processed template for current INNER item
    return tmp;
  });
  // color counter is not a part of JSON, so we output it as custom value
  tmp = tmp.replace("{CountColors}", item.colors.length);
  // return processed template for current item
  return tmp;
});
// put processed output back
document.getElementById("example").innerHTML = tmp;</pre>

This looks very promising.  In fact, this could be a very cool way of writing reports in jQuery!  Think about it – with a tool like jLinq for filtering data sets and jsRazor, you could replace SQL Server Reports.

Advertisements

The Speed of Thought, Part Duh!!! (Or Driving Stick Shift with Javascript) April 18, 2013

Posted by ActiveEngine Sensei in ActiveEngine, Coaching, Humor, jQuery, KnockoutJS, Mythology, Problem Solving, Scripting.
Tags: , , , , ,
add a comment

scream_baron_blood_01Sensei is a libertarian – so you can interpret that to mean few rules, respect others freedom, government and busy bodies “leave me the hell alone”, stay-outta-my-way-attitude-person is his motto.  That means the only way to drive is with the stick.  Automatic is for the soccer moms.  Javascript is like driving manual transmission – sometimes you grind the gears.

You’re hero just spent a half hour pouring over some Knockout.js code, wondering why his observableArray went MIA on each push.  Can you see why?

var Question = function (id, question, sortOrder) {
this.Id = id;
this.Question = ko.observable(question);
this.SortOrder = ko.observable(sortOrder);
};

It’s not Javascript’s fault, it’s Sensei’s fault. Now you can see why he writes in the third person, ’cause it’s easier to remove yourself from these type of dumb mistakes when you can treat your persona as separate person!! If you see the issue, leave a comment before I post the resolution.

Some Pitfalls To Avoid With KnockoutJS “options” Binding September 8, 2012

Posted by ActiveEngine Sensei in ActiveEngine, Ajax, KnockoutJS, Mythology, New Techniques, Open Source, Tutorial.
Tags: , , , , , , , , , ,
add a comment

As Sensei has written earlier, KnockOutJS is a great framework for creating rich client side solutions for you web applications.  Simply said it cuts your development down considerably by performing CSS binding for you, while also bringing better structure to your Javascript through the use of the MVVM pattern.  But even the greatest of all wizardry, magery, grammary, magik has its stumbling blocks.  Each tool you use constrains you in some way.  This week Sensei uncovered another puzzle that has left him wondering still if he found the best solution.  Maybe you will have some insight you can share with the “options” binding from Knockout.

Here is the scenario:  You have a <select> ( or a drop down list as us old school Windows devs are found of saying) that you wish to populate with values from an array.  There are two ways that this select list will be used.  The first is when you create a record, and naturally you would like the list to display “New …”.  The second goal is set the value of the <select> to match the value of a current record.  Here is the JS-Fiddle with the first attempt. Selecting from the list sets the value, and you’ll the update at the bottom. Clicking “Simulate Editing Amys Record” will set the value of the list to “Amy” as though you were performing an edit operation.  Here is the view model code:


var ViewModel = function() {
var self = this;

// Simulated seed data from server
this.seedData = ko.observableArray([
{
ID: 1,
firstName: 'John',
value: '333'},
{
ID: 2,
firstName: 'Bob',
value: '333'},
{
ID: 3,
firstName: 'Amy',
value: '333'}]),

// Simulated data from server
self.data = {
title: ko.observable('This is a sample'),
selectedValue: ko.observable("")
}

self.prepForNew = function() {
self.data.selectedValue("");
}

self.changeIt = function() {
self.data.selectedValue("Amy");
}

};

var vm = new ViewModel();
ko.applyBindings(vm);

Now bear with Sensei as he describes the behavior that was so confounding.  We are initializing the <select> by setting data.selectedValue(“”).  The first time the page is displayed we get the behavior that we want.  Click the “Set List for New Record List”.  Nothing happens.  If you trace with Firebug you’ll see that the value is indeed being set, but once it leaves the method it reverts to the current value in the <select>.

Speak, friend, and enter …

Oookkay. Scratch your head. Walk away. Come back, fiddle so more. Rinse, then repeat for about 5 hours.  This shouldn’t be.  In his frenzy Sensei did not consult StackOverflow.  At last an idea came to mind.  Why not add “New …” as the first entry in <select>, give a value of -1 and an ID of -1.  This way at least it is identifiable.  Seems silly but when you have things to accomplish sometimes you just have to eat the sausage instead of thinking about how its made.  Check out the new JS Fiddle before Sensei explains.

Three simple changes have occured.  First we cheate by adding a new object to the array that supports our <select>.  We gave it the “New …” as the first element.

this.seedData = ko.observableArray([
{
//  Here is the default caption object
ID: -1,
firstName: 'New ...',
value: ''},
{
ID: 1,
firstName: 'John',
value: '333'},
{
ID: 2,
firstName: 'Bob',
value: '333'},
{
ID: 3,
firstName: 'Amy',
value: '333'}]),

We yanked out the “optionsCaption: ‘New …” entry in the HTML mark for the view.  Finally the altered the method self.prepForNew to set the value of selectedValue to “New …” with the statement selectedValue(“New …”);  This forces KnockOut to sync to what we want.  Remember that we are working with methods when setting values with Knockout, hence the use of (“New …”);

Sensei is happy to have things working.  Being perplexed over finding out the cause instead of simply creating something simple did fret away the hours.  Like with any new tool, there are nuances that won’t become apparent until you are hit over the head with their pitfalls.

%d bloggers like this: