The process of remote databinding is often quite frustrating. With new WebApi features, the JSON data is easily availble, but the actual binding of data to a form has become more difficult.
Kendo UI and Angular both offer similar data-binding features for their MVVM forms. While I generally prefer to simply load my own data using $.ajax, It is imperative that forms be made using a more professional wrapper if they are to be understood among multiple developers and reduce the long-term costs of support.
Here is a very basic MVVM form with remote binding.
Package Editor
The only part I’m going to focus on today is populating these fields. We’re going to use Kendo’s DataSource object.
var myurl="/api/some-test-json" var localDataSource = new kendo.data.DataSource({ transport: { read: { url: myurl, dataType: "json" } }});
Now, since I want a working demo, I’m going to use mockJax to emulate the actual json provider
var myurl="/api/some-test-json" $.mockjax({ url: myurl, responseTime: 750, responseText:[{"package_id":"13","code":"SCREEN PKG","package_name":"Screen Package","package_desc":"Screen Package with AC ext.cord and power strip, and skirted cart ","price_level_a":"110.0000","price_level_b":"0.0000","price_level_c":"0.0000","price_level_d":"0.0000","price_level_e":"0.0000","commission_type_id":"1"}] }); var mydata = new kendo.data.DataSource({ transport: { read: { url: myurl, dataType: "json" } }});
So that will set us up to bring some data to the page, but we now have to jam that into an object that can be linked to the page. For this, we use Kendo’s “Observable”. There are a lot of features to an observable beyond just data, but we’ll focus on data for now.
var viewModel = kendo.observable({ packageSource: mydata });
Now, that will set up the observable object to read the data, but it doesn’t bind it to the form, nor does it actually read any data.
Here’s how we do both:
kendo.bind($("#view"), viewModel); mydata.read()
Remember, nothing actually goes to the form until you READ THE DATA. You can bind it whenever you want. As soon as it’s bound, changes to the data will flow into the form and vice-versa.
What is EXTREMELY important to remember is the level at which the binding takes place. Your data will be within the “data” function of the observable’s datasource.
examine below:
My field in JSON for “code” must be preceded by “packageSource.data()[0].”.
The only benefit here is that we can actually use multiple remote datasources within an observable. That even allows a great mixture of local data and remote data. That way you can have local arrays for all your dropdowns, but the values within the primary datasource.
It is this flexibility and manageability which ends up being the cost-saver. If all developers know where to look for datasources and track down issues, then the time cost is reduced.
Here is a working example:
Our next project will review how to connect this form to an update API.