This is a migrated thread and some comments may be shown as answers.

Generic form field binding

2 Answers 142 Views
MVVM
This is a migrated thread and some comments may be shown as answers.
Franz
Top achievements
Rank 1
Franz asked on 20 Jun 2012, 12:36 PM
I want to implement a generic form field binding with kendo MVVM. This means that my model shouldn't contain any hard-wired field IDs in its bindings, instead it should be able to bind to any form rendered by the server. Here is what I've got so far:

var genericModel = {};
function bindField($field) {
    var viewModel = kendo.observable({
        value: "John Doe"
    });
    $field.attr('data-bind', 'value: value');
    kendo.bind($field, viewModel);
   genericModel[$field.attr('id')] = viewModel;
}
 
 
$(function () {
    var $inputs = $('input').not('.datetimepicker, .autocomplete');
    $inputs.each(function () {
        bindField($(this));
    });
});

This code iterates through all input fields, attaches the necessary data-bind attributes to them and sets up the model binding for each field. Finally all field objects are stored in the global genericModel object.

Unfortunately, this approach doesn't seem to work - changes aren't updated in both directions. I also tried the "nested binding" approach mentioned in the docs but had no luck either. I'm using KendoUI v2012.2.531

Any idea?

Thanks,

Franz

2 Answers, 1 is accepted

Sort by
0
Franz
Top achievements
Rank 1
answered on 21 Jun 2012, 07:50 AM
finally i had success using the "nested" approach:

var genericModel = {};
function bindField($field) {
   var fieldId = $field.attr('id');
   genericModel[fieldId] = {value: 'test'};
   $field.attr('data-bind', 'value: ' + fieldId + '.value');
}
  
  
$(function () {
    var $inputs = $('input').not('.datetimepicker, .autocomplete');
    $inputs.each(function () {
        bindField($(this));
    });
    kendo.bind($('form'), genericModel);
});
0
Peter Bulloch
Top achievements
Rank 1
answered on 22 Jun 2012, 07:18 PM
Franz, can you post you entire code please?  I'm also having challenges with MVVM and am looking for best practices. Ideally I'd like to focus on the 2012 Q2 beta release.
Tags
MVVM
Asked by
Franz
Top achievements
Rank 1
Answers by
Franz
Top achievements
Rank 1
Peter Bulloch
Top achievements
Rank 1
Share this question
or