Dynamic Item ViewModel Knockout - javascript

I have a lot of (KnockOut) view models that get data from a rest service and then populate "item" view models that are pretty much simple and just contain the fields coming from the REST interface.
I was just wondering if there was a way to not having to define the item viewmodels but somehow just create them dynamic as objects (where each property is an observable).
So in the example below I would want to not have the "ItemViewModel" but just say within the AddItems function that it should create an object based on the data and make each entry an ko.observable. the passed "itemName" then contains "ItemViewModel1" (or in other call "ItemViewModel2" ...etc).
So e.g. if the Json Rest input has a field "LAST_NAME" it would add self.LAST_NAME = ko.observable()" filled with that value etc. (so I can still reference it in the views).
var ItemViewModel1 = function (data) {
var self = this;
self.PAR1 = ko.observable(data.PAR1)
self.PAR2 = ko.observable(data.PAR2)
self.PAR3 = ko.observable(data.PAR3)
self.PAR4 = ko.observable(data.PAR4)
// … etc
}
var MasterViewModel1 = function (data) {
var self = this;
ReportBaseViewModel.call(self)
}
var ReportBaseViewModel = function () {
var self = this;
/* commonly used vars */
self.report = ko.observable();
self.searchedCallBackFunction = ko.observable();
self.items = ko.observableArray();
self.selecteditem = ko.observable();
self.selectedPerson = ko.observable();
/* method: print */
self.PrintEventHandler = function (data) { window.print(); };
/* method: add items to array */
self.AddItems = function (data) {
var newitems = ko.utils.arrayMap(data, function (item) {
c = new window[self.itemname](item);
return c;
});
self.items(newitems);
};
/* eventhandler: select one item */
self.SelectEventHandler = function (item) {
selecteditem(item);
};
self.GetReport = function (selectedPerson, viewContainer, url, itemName) {
self.selectedPerson(selectedPerson);
self.itemname = itemName;
var jqxhr = $.ajax({
url: url,
type: "GET"
}).done(function (data, textStatus, jqXHR) {
if (data != null) {
self.AddItems(data);
$('#' + viewContainer).show();
document.getElementById(viewContainer).scrollIntoView();
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log('fail' + JSON.stringify(jqXHR));
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-top-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "0",
"hideDuration": "1000",
"timeOut": "0",
"extendedTimeOut": "0",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
toastr["error"]("ERROR");
}).always(function (jqXHR, textStatus, errorString) {
if (typeof self.searchedCallBackFunction() === 'function') {
self.searchedCallBackFunction();
}
});
}
}

There is. If your objects are simple and not nested, you can write the code to map them yourself:
var someJSON = '{ "firstName": "John", "lastName": "Doe" }';
var makeSimpleVM = function(obj) {
// Return a new object with all property
// values wrapped in an observable
return Object
.keys(obj)
.reduce(function(vm, key) {
vm[key] = ko.observable(obj[key]);
return vm;
}, {});
};
var myVM = makeSimpleVM(JSON.parse(someJSON));
console.log(ko.isObservable(myVM.firstName)); // true
console.log(myVM.firstName()); // John
myVM.firstName("Jane");
console.log(myVM.firstName()); // Jane
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
I think it's important to read through this naive implementation: it makes you understand why it's probably a better idea to use a ready-made plugin.
As soon as your server side code contains arrays, nested viewmodels or any properties that you don't want mapped, you'll run in to problems. The ko.mapping plugin has already solved these problems for you. It maps arrays to ko.observableArrays and lets you specify mapping strategies.
var someJSON = '{ "firstName": "John", "lastName": "Doe" }';
// Let's use the library this time
var myVM = ko.mapping.fromJS(JSON.parse(someJSON));
console.log(ko.isObservable(myVM.firstName)); // true
console.log(myVM.firstName()); // John
myVM.firstName("Jane");
console.log(myVM.firstName()); // Jane
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>

You could try using the mapping plugin or the Json functions, depending on what exactly you are looking for. I think what you are looking for is the mapping plugin:
http://knockoutjs.com/documentation/plugins-mapping.html
http://knockoutjs.com/documentation/json-data.html

Related

Javascript push array inside object

How do I create the data array from my second api call result into the format I want?
I have a code like this
var github = require('octonode');
var client = github.client();
var userName = "octocat";
var repoName = "";
var branchName = "";
var data = [];
var branches = [];
client.get('/users/'+userName+'/repos', {}, function (err, status, body, headers) {
body.forEach(function(obj) {
repoName = obj.name;
//==============================
client.get('repos/'+userName+'/'+repoName+'/branches', {}, function (errx, statusx, bodyChild, headersx) {
bodyChild.forEach(function(objChild) {
branchName = objChild.name;
});
});
});
});
I have received repoName and branchName data as well.
I want my data format like
How to use
data.push({
name: repoName,
branches: 'branchName loooping here for every repoName'
});
so branches repetition data can be contained in my branches tag
Thank you
I guess you can do something like this:
var data = [];
client.get('/users/'+userName+'/repos', {}, function (err, status, body, headers) {
body.forEach(function(obj) {
repoName = obj.name;
client.get('repos/'+userName+'/'+repoName+'/branches', {}, function (errx, statusx, bodyChild, headersx) {
let elem = {"name": repoName, "branches": []}; //create json object for each repo
bodyChild.forEach(function(objChild) {
elem.branches.push(objChild.name); //push all branchs to that elem
});
data.push(elem); // add the elem to the data array
});
});
});
So in this case data is an object, that has a property name which is string, and another property branches which is array. If you want to push data to the property branches you can just call the push() function on it.
Please check the example below:
let data = {
name: "repoName",
branches: [
{
name: "foo"
}
]
}
data.branches.push(
{
name: "bar"
}
);
console.log(data);

Knockout.js Adding a Property to Child Elements

My code doesn't create a new property under the child element of knockout viewmodel that is mapped by knockout.mapping.fromJS.
I have:
//model from Entity Framework
console.log(ko.mapping.toJSON(model));
var viewModel = ko.mapping.fromJS(model, mappingOption);
ko.applyBindings(viewModel);
console.log(ko.mapping.toJSON(viewModel));
The first console.log outputs:
{
"Id": 0,
"CurrentUser": {
"BoardIds": [
{
"Id": 0
}
],
"Id": 1,
"UserName": "foo",
"IsOnline": true
},
"Boards": []
}
And then the mappingOption is:
var mappingOption = {
create: function (options) {
var modelBase = ko.mapping.fromJS(options.data);
modelBase.CurrentUser.UserName = ko.observable(model.CurrentUser.UserName).extend({ rateLimit: 1000 });
//some function definitions
return modelBase;
},
'CurrentUser': {
create: function (options) {
options.data.MessageToPost = ko.observable("test");
return ko.mapping.fromJS(options.data);
}
}
};
I referred to this post to create the custom mapping, but it seemed not working as the second console.log outputs the same JSON to the first one.
Also, I tried to create nested mapping option based on this thread and another one but it didn't work too.
var mappingOption = {
create: function (options) {
//modelBase, modifing UserName and add the functions
var mappingOption2 = {
'CurrentUser': {
create: function (options) {
return (new(function () {
this.MessageToPost = ko.observable("test");
ko.mapping.fromJS(options.data, mappingOption2, this);
})());
}
}
}
return ko.mapping.fromJS(modelBase, mappingOption2);
}
};
How can I correctly add a new property to the original viewmodel?
From the mapping documentation for ko.toJS (toJS and toJSON work the same way as stated in the document)
Unmapping
If you want to convert your mapped object back to a regular JS object, use:
var unmapped = ko.mapping.toJS(viewModel);
This will create an unmapped object containing only the properties of the mapped object that were part of your original JS object
If you want the json to include properties you've added manually either use ko.toJSON instead of ko.mapping.toJSON to include everything, or use the include option when first creating your object to specify which properties to add.
var mapping = {
'include': ["propertyToInclude", "alsoIncludeThis"]
}
var viewModel = ko.mapping.fromJS(data, mapping);
EDIT: In your specific case your mapping options are conflicting with each other. You've set special instructions for the CurrentUser field but then overridden them in the create function. Here's what I think your mapping options should look like:
var mappingOption = {
'CurrentUser': {
create: function (options) {
var currentUser = ko.mapping.fromJS(options.data, {
'UserName': {
create: function(options){
return ko.observable(options.data);
}
},
'include': ["MessageToPost"]
});
currentUser.MessageToPost = ko.observable("test");
return ko.observable(currentUser).extend({ rateLimit: 1000 });
}
}
};
and here's a fiddle for a working example

IndexedDB and Javascript: JSON and objects misunderstanding

I'm trying to obtain information from a JSON file download to the client through AJAX and I'm getting different results depending on the JSON format and I don't know how to fix the one with problem.
First case:
The json files looks like:
[{"name": "nick",
"age": 28},
{"name": "katie",
"age": 32}]
My AJAX .done method looks like:
.done(
function(data) {
addObjectsDB (data, "people");
})
This method calls a second one that iterates through data and stored correctly each object into IndexedDB.
Second case:
Now I have a JSON file with different format:
[
{
"husband": {
"name": "Jhon",
"age": 23 },
"wife": {
"name": "Marie",
"age": 24 }
}
]
Now my .done() AJAX method iterates through data and add each person, husband or wife to an array which is then sent to the DB with the same method than the first case:
.done(
function(data) {
var people = [];
$(data).each(function (key, value){
people.push(value.husband);
people.push(value.wife);
});
addObjectsDB (people, "people");
})
In this case the insertion into the database fails, if for example, instead of adding value.husband to people array I just add value to people array the insertion works, but I need each person stored separated in the DB.
The addObjectsDB method is:
function addObjectsDB (data, collection) {
var objectStore = db.transaction(collection, "readwrite").objectStore(collection);
$.each (data, function (key, value) {
var request = objectStore.add(value);
});
}
As I said the first case works perfectly but the second one inserts nothing and no error is showed...
I think the problem is that I don't understand javascript types adequately but I'm starting with it and I've spent a whole evening with it.
There's nothing wrong with your IDB code. Look for your answer in the code you haven't presented, particularily the AJAX response (is your JSON parsed the way you think it is?)
Be sure to attach event listeners for the error event. I'm positive that if your IDB "inserts nothing" then in fact it's not true that "no error is showed" and rather no error is seen due to callback mismanagement.
Here's a working implementation, modified from a previous answer I've given on this tag. This implementation doesn't have the uniqueness constraints you've put on your schema on purpose: it shows that your looping is fine. The entries below all look good.
var db_name = 'SO_22977915',
store_name = 'people';
$.ajax({
url: '/echo/json/',
type: 'post',
dataType: 'json',
data: {
json: JSON.stringify({
case1: [{
"name": "nick",
"age": 28
}, {
"name": "katie",
"age": 32
}],
case2: [{
"husband": {
"name": "Jhon",
"age": 23
},
"wife": {
"name": "Marie",
"age": 24
}
}]
})
},
success: function (data) {
var request,
upgrade = false,
doTx = function (db, entry) {
addData(db, entry, function () {
getData(db);
});
},
getData = function (db) {
db.transaction([store_name], "readonly").objectStore(store_name).openCursor(IDBKeyRange.lowerBound(0)).onsuccess = function (event) {
var cursor = event.target.result;
if (null !== cursor) {
console.log("entry", cursor.value);
cursor.continue();
}
};
},
addData = function (db, entry, finished) {
console.log('adding', entry);
var tx = db.transaction([store_name], "readwrite"),
people = [];
tx.addEventListener('complete', function (e) {
finished();
});
$.each(entry.case1, function (key, value) {
tx.objectStore(store_name).add(value);
});
$(entry.case2).each(function (key, value){
people.push(value.husband);
people.push(value.wife);
});
$.each(people, function (key, value) {
tx.objectStore(store_name).add(value);
});
};
request = window.indexedDB.open(db_name);
request.oncomplete = function (event) {
if (upgrade) {
doTx(request.result, data);
}
};
request.onsuccess = function (event) {
if (!upgrade) {
doTx(request.result, data);
}
};
request.onupgradeneeded = function (event) {
var db = event.target.result;
db.createObjectStore(store_name, {
keyPath: null,
autoIncrement: true
});
}
}
});
A cursor and console.log shows all entries as being added:

Reference var from one model to another returns defaults in Backbone

I have a model which sets the defaults like so:
var CampModel = Backbone.Model.extend({
defaults: {
siteID: $.jStorage.get('currentSiteID'),
active: -1,
pending: -1,
},
url: function () {
//some url.
},
sync: function (method, model, options) {
var method = 'read';
var that = this,
options = options || {};
options.success = function(model, response, options){
if(response.errorMessage != "Session is over")
console.log('Update session');
if(response.success)
if(response.returnValue.length){
that.set('response', response.returnValue);
that.CountActiveAndPending(response.returnValue);
}
else {
that.set('response', []);
}
else console.log('report: bad request, error: '+ response.errorMessage);
}
Backbone.sync(method, model, options);
},
},
//Counts active and pending campaigns for front page.
CountActiveAndPending: function (data) {
var active = 0;
var pending = 0;
//var it = this;
$.each(data, function (index, val) {
if (val.ApprovedOnSite) active++;
else pending++;
});
this.set('active', active);
this.set('pending', pending);
}
});
and in a different model I try and get the models parameters like so:
this.set({
campModel: new CampModel(),
})
});
this.get('campModel').save();
console.log(this.get('campModel').get('active'));
},
Everything seems to run great but when I try to get the "active" param from the CampModel I get the -1 default value and not the value assigned in the model. Any thoughts as to why this happens?
Model#save is asynchronous, when you're doing:
console.log(this.get('campModel').get('active'));
the server hasn't responded yet, so CountActiveAndPending has never been called and active is still -1. Try to log its value in your success callback.

Store json data in a variable inside a proxy pattern

I have this code:
var my = {};
(function () {
var self = this;
this.sampleData = { };
this.loadData = function() {
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
{tags: "cat", tagmode: "any", format: "json"},
function(data){
self.sampleData = data;
}
);
};
}).apply(my);
my.loadData();
console.log(my.sampleData); // {}
The problem is my.sampleData not have anything.
Try this sample here: http://jsfiddle.net/r57ML/
The reason is that the getJSON call is asynchronous, so you're looking for the data before it's been returned. Instead, put your code using the data inside the callback, either directly or indirectly.
For instance, you can have your loadData call accept a callback:
var my = {};
(function () {
var self = this;
this.sampleData = { };
this.loadData = function(callback) {
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
{tags: "cat", tagmode: "any", format: "json"},
function(data){
self.sampleData = data;
callback(); // <==== Call the callback
}
);
};
}).apply(my);
my.loadData(function() { // <=== Pass in a callback
console.log(my.sampleData); // Now the data is htere
});
Side note: Since your my object is a singleton, you can simplify that code a fair bit, no need for apply, this, or self, since your anonymous function is a closure over the context in which my is defined:
var my = {};
(function () {
my.sampleData = { };
my.loadData = function(callback) {
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
{tags: "cat", tagmode: "any", format: "json"},
function(data){
my.sampleData = data;
callback();
}
);
};
})();
my.loadData(function() {
console.log(my.sampleData); // Now the data is htere
});
Of course, if you're using a constructor function or something instead (you weren't in your quoted code, but...), then of course you might need the more complex structure.
(function () {
var self = this;
this.sampleData = {};
this.loadData = function() {
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
{tags: "cat", tagmode: "any", format: "json"},
function(data){
self.sampleData = data;
console.log(my.sampleData); // you get sample data after ajax response
},
'json');
};
}).apply(my);
my.loadData();

Categories

Resources