Question

I have a Model with ~30 data bound properties. I'm looking for a best practice pattern of model binding in KO. I know I can do this:

Fiddle

HTML

<div>First Name</div>
<input type="text" data-bind="value: FirstName, valueUpdate: 'afterkeydown'" />
<div>Last Name</div>
<input type="text" data-bind="value: LastName, valueUpdate: 'afterkeydown'" />
<div>Full Name</div>
<input type="text" data-bind="value: FullName" />

JavaScript

ko.applyBindings(new viewModel());

function viewModel(){
    var self = this;
    //var model = {};
    var model = {
        FirstName : "bubba",
        LastName : "gump"
    };

    bindModel(self, model);
}

function bindModel(self, model) {
    if(model.FirstName){
        self.FirstName = ko.observable(model.FirstName);    
    }else{
        self.FirstName = ko.observable('');    
    }
    if(model.LastName) {
        self.LastName = ko.observable(model.LastName);        
    }else{
        self.LastName = ko.observable('');       
    }

    self.FullName = ko.computed(function(){        
    return self.FirstName() + " " + self.LastName();}
                                , self);   
}

Is there an extension, pattern or best practice that takes care of this verbose null checking or other setup gobbly gook? This is a single page app. If I'm looking at the page in one way I bind to a model. If I'm looking at it another way I bind to nothing at all (binding happens in AJAX later).

Was it helpful?

Solution

Are you just not wanting to set any of those properties equal to null? The view will treat '' the same as null so it is more than Ok to just set it equal to the property.

If you are just looking for short hand you can always do this -

self.LastName = ko.observable(model.LastName ? model.LastName : '');

Or if you are looking to re-use it you can do this -

self.LastName = makeObservable(model.LastName);
self.FirstName = makeObservable(model.FirstName);

function makeObservable(prop) {
    return ko.observable(prop ? prop : '');
}

Last, you can always use the mapping plugin to map your data and just override how you want it to map.

http://knockoutjs.com/documentation/plugins-mapping.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top