knockout
by danne567
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.3.0.js"></script>
<div data-bind="with: customerModel">
<div data-bind="text: name"></div>
<div data-bind="text: address1"></div>
<div data-bind="text: address2"></div>
<div data-bind="text: town"></div>
</div>
JavaScript
(function () {
var $loader = $('<div>', {id: 'loader', text: 'loading'}).hide().appendTo('body');
var dataservice = {
getData: function () {
// Mocking ajax call.
return $.Deferred(function(def) {
$loader.show();
setTimeout(function () {
$loader.hide();
def.resolve({
name: 'Some name',
address1: 'Address1',
address2: 'Address2',
town: 'Town'
});
}, 1000);
}).promise();
}
};
var CustomerModel = function (data) {
this.name = ko.observable('');
this.address1 = ko.observable('');
this.address2 = ko.observable('');
this.town = ko.observable('');
this.init(data);
};
CustomerModel.prototype = {
init: function (data) {
if (!data) return;
this.name(data.name);
this.address1(data.address1);
this.address2(data.address2);
this.town(data.town);
}
}
var ViewModel = function () {
var self = this;
this.customerModel = new CustomerModel();
this.getData = function() {
dataservice.getData()
.done(function(result) {
self.customerModel.init(result);
});
};
};
var vmInstance = new ViewModel();
ko.applyBindings(vmInstance);
vmInstance.getData();
})();