MVVM Pattern

When you build the MVC project you might wish to send the data as min to the browser, and let the browser help rendering the view for you.

The early stage i’m trying to binding the JSON data using jQuery, as the times goes when you create couple pages. this process is getting irritating since it’s keep repeating.

$.each(json, function (i, item)
            {
                html += "<tr>"
                     + "<td><input type='checkbox' id='" + item.Id + "' class='checkboxGroups'></input></td>"
                     + "<td>" + item.LogLevel + "</td>"
                     + "<td>" + item.ShortMessage + "</td>"
                     + "<td>" + toReadableDateTime(item.CreatedOn) + "</td>"
                     + "<td><a href='View/" + item.Id + "'>View</a></td>"
                     + "</tr>";
            });

The better solution is to use any MVVM pattern to help you binding all the JSON object into the webpages, most of the process you need to do 2 things.
1. Bind Data in the HTML

tbody id="tbody" data-bind="foreach: log">
                        <tr>
                            <td><input type="checkbox" data-bind="attr: { 'id': Id, 'class': 'checkboxGroups' }" /></td>
                            <td data-bind="text: LogLevel"></td>
                            <td data-bind="text: ShortMessage"></td>
                            <td data-bind="text: toReadableDateTime(CreatedOn)"></td>
                            <td><a data-bind="attr: { 'href': 'View/' + Id }">View</a></td>
                        </tr>
                    </tbody>

2. Apply Bindings

var viewModel = {
        log: ko.observableArray([]) //Create the Observable View Model
    };
    ko.applyBindings(viewModel); //Apply Binding

//Ajax
$.ajax(options).done(function(json) {
            viewModel.log(json.Data); //Putting into the viewModel
            //Paging(json.PageSize, json.Total, json.PageIndex);
        });
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s