knockout js. foreach children of a child not working - javascript

I am having trouble iterating over my json data with knockout.
My view model looks like :
var ViewModel = function () {
var self = this;
self.Summary = ko.observableArray();
$.getJSON('some api url', function(result) {
ko.mapping.fromJS(result, {}, self);
});
}
ko.applyBindings(new ViewModel());
My JSON data looks like :
{
Summary: {
Details: [
{
Name: "Foo",
Id: 1,
Detail: "Some Data"
},
{
Name: "Bar",
Id: 2,
Detail: "Another Data"
}
],
SummaryOverview: "BlahBlah",
AnotherObject: [
{
Name: "My Name"
AnotherChildObject: [
{
name:"some name"
}
]
}
]
}
}
My question is do I iterate thru my data this way:
<div data-bind="foreach: Summary">
<div data-bind="text: Details.Detail"></div>
</div>
OR
<div data-bind: "foreach: Summary.Details">
<div data-bind="text: Detail"></div>
</div>
How do I display the Detail? The HTML above is not working for me.
Thank you very much!!

The problem with ko.mapping is that your observables will be replaced with new observables. To clarify, the Summary, which is an observableArray, will be replaced by a new observableArray by ko.mapping.
There are two ways to remedy this. The first alternative is to wait with the applyBindings until the real array has been created:
var ViewModel = function () {
var self = this;
// no need to set the array, it will be overwritten anyway
// self.Summary = ko.observableArray();
}
var vm = new ViewModel();
$.getJSON('some api url', function(result) {
ko.mapping.fromJS(result, {}, vm);
ko.applyBindings(vm);
});
Alternative 2 is to bootstrap the viewmodel with initial (empty) data. If you apply ko.mapping on an empty array, the next call to ko.mapping will update the existing array rather than overwrite it. Like so:
var ViewModel = function () {
var self = this;
var init = { Summary: [] };
ko.mapping.fromJS(init, {}, self);
$.getJSON('some api url', function(result) {
ko.mapping.fromJS(result, {}, self);
});
}
ko.applyBindings(new ViewModel());
I usually go with alternative 2. Alternative 1 will cause a delay before ko.applyBindings is called, which might cause some UI flicker (and unwanted elements may be visible, etc).

Related

Bind knockoutjs to javascript object property

I'm new to Knockoutjs, so please bear with me.
I want to knocoutjs bind a DxForm (DevExpress) to an javascript object property, but I get an error ... "Cannot read property 'items' of undefined".
I am uncertain if this is a knockout problem, DevExpress problem or just incufficient coding skills from my part.
Here's my code...
HTML:
<div data-bind="dxForm: frm.options"></div>
Javascript:
var viewModel = function() {
var that = this;
// -----------------------------------------------------------------
// Faste...
// -----------------------------------------------------------------
that.frm = {
items: ko.observable(undefined),
data: ko.observable(undefined),
instance: ko.observable({}),
options: {
items: that.frm.items,
formData: that.frm.data,
onInitialized: function(e) {
that.frm.instance(e.component);
},
},
};
return {
frm: that.frm,
};
};
var vm = new viewModel();
ko.applyBindings(vm);
var items = [{
"dataField": "test",
"editorOptions": {
"type": "date",
"pickerType": "calendar",
},
"editorType": "dxDateBox",
"name": "Test",
"visible": true
}];
var data = {
test: 10,
};
vm.frm.data(data);
vm.frm.items(items);
JSFiddle: https://jsfiddle.net/MojoDK/ke395v2c/3/
I want to bind to objects since I'm going to use several DxForm objects and I like to keep the code to each DxForm in an object (easier to read).
Any idea why it fails?
Thanks.
You just have a problem with closure in your frm.
The that property in frm object do not exist you should use this...
But in your onInitialized function, this and that will not target your viewModel object...
So this way, the easiest is to declare options object later :
that.frm = {
items: ko.observable(undefined),
data: ko.observable(undefined),
instance: ko.observable({})
};
that.frm.options = {
items: that.frm.items,
formData: that.frm.data,
onInitialized: function(e) {
that.frm.instance(e.component);
},
};
Updated jsfiddle

Bind OracleJet ojtimeline component to viewModel

I am trying to understand how I can bind data from the view-model to the view. The REST request to the back-end is working fine and I get a JSON array with several items. The existing documentation doesn't give me enough help.
How can I bind the timeline component ojtimeline to the view-model data array?
Edit: No errors now, since the view recognize the view-model array. But the ojtimeline doesn't display the data, only a working empty view component.
View
<div id="tline"
data-bind='ojComponent: {
component: "ojTimeline",
minorAxis: {
scale: "hours",
zoomOrder: ["hours", "days", "weeks"]
},
majorAxis: {
scale: "weeks"
},
start: new Date("Jan 1, 2016").toISOString(),
end: new Date("Jun 31, 2016").toISOString(),
referenceObjects: [{value: new Date("Feb 1, 2010").toISOString()}],
series: [{
id: "id",
emptyText: "No Data.",
items: statusArray,
label: "Oracle Events"
}],
overview: {
rendered: "off"
}
}' style="width: '100%';height: 350px"></div>
View-model
define(['ojs/ojcore', 'knockout', 'jquery', 'ojs/ojknockout', 'ojs/ojtimeline'],
function (oj, ko) {
/**
* The view model for the main content view template
*/
function timelineContentViewModel() {
var self = this;
this.statusArray = ko.observableArray([]);
self.addData = function () {
$.ajax({
url: "http://localhost:8080/myproject/rest/status/v1/findAll",
type: 'GET',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
var x = data;
for (i = 0; i < x.length; i++) {
statusArray.push({
id: data[i].id,
description: data[i].text,
title: data[i].user.screenName,
start: data[i].createdAt});
}
//$("#tline").ojTimeline("refresh"); Doesn't have ant affect
}
});
};
self.addData();
}
return timelineContentViewModel;
});
The ReferenceError is caused by
var statusArray = ko.observableArray([]);
it should be
this.statusArray = ko.observableArray([])
You will also (probably) need to refresh the timeline when the observable array has changed, e.g. after the for-loop in success callback:
...
success: function (data, textStatus, jqXHR) {
var x = data;
for (i = 0; i < x.length; i++) {
self.statusArray.push({
id: data[i].id,
description: data[i].text,
title: data[i].user.screenName,
start: data[i].createdAt});
}
$("#tline").ojTimeline("refresh");
}
...
I have loaded ojTimeline from Ajax data and have never needed to use refresh. Worst case, you can wrap the ojTimeline in a <!-- ko if ... --> so that the timeline doesn't appear until you have an Ajax response.
For the ojTimeline items attribute, instead of referencing the observable, I had to unwrap the observable like this: items: ko.toJS(statusArray).
Another thing to consider is pushing into an ko.observableArray inside a for loop. Each push using the ko.observableArray push() method invokes subscriptions. If your array is bound to the UI, then each push will trigger a DOM change. Instead, it is often better to push into the underlying array (unwrap the array) and then invoke self.statusArray.valueHasMutated. You may also want to keep an eye on your use of this, self, and nothing. Consistency will help avoid bugs like the one ladar identified.
What do you think about rewriting your for loop like this (code untested)?
ko.utils.arrayPushAll(
self.statusArray(),
ko.utils.arrayMap(data, function(item) {
return {
id: item.id,
description: item.text,
title: item.user.screenName,
start: item.createdAt;
};
});
);
self.statusArray.valueHasMutated();
Or, if you can get away with it (some OJ components don't like this approach), you can skip the push and just replace the entire array inside the observable:
self.statusArray(
ko.utils.arrayMap(data, function(item) {
return {
id: item.id,
description: item.text,
title: item.user.screenName,
start: item.createdAt;
};
});
);

kendo ui - create a binding within another binding?

In my pursuit to get a binding for an associative array to work, I've made significant progress, but am still blocked by one particular problem.
I do not understand how to create a binding from strictly javascript
Here is a jsFiddle that shows more details than I have posted here:
jsFiddle
Basically, I want to do a new binding within the shown $.each function that would be equivalent to this...
<div data-template="display-associative-many" data-bind="repeat: Root.Items"></div>
Gets turned into this ...
<div data-template="display-associative-single" data-bind="source: Root['Items']['One']"></div>
<div data-template="display-associative-single" data-bind="source: Root['Items']['Two']"></div>
<div data-template="display-associative-single" data-bind="source: Root['Items']['Three']"></div>
And I am using the repeat binding to create that.
Since I cannot bind to an associative array, I just want to use a binding to write all of the bindings to the objects in it.
We start again with an associative array.
var input = {
"One" : { Name: "One", Id: "id/one" },
"Two" : { Name: "Two", Id: "id/two" },
"Three" : { Name: "Three", Id: "id/three" }
};
Now, we create a viewModel that will contain that associative array.
var viewModel = kendo.observable({
Name: "View Model",
Root: {
Items: input
}
});
kendo.bind('#example', viewModel);
Alarmingly, finding the items to bind was pretty easy, here is my binding so far;
$(function(){
kendo.data.binders.repeat = kendo.data.Binder.extend({
init: function(element, bindings, options) {
// detailed more in the jsFiddle
$.each(source, function (idx, elem) {
if (elem instanceof kendo.data.ObservableObject) {
// !---- THIS IS WHERE I AM HAVING TROUBLE -----! //
// we want to get a kendo template
var template = {};// ...... this would be $('#individual-item')
var result = {}; // perhaps the result of a template?
// now I need to basically "bind" "elem", which is
// basically source[key], as if it were a normal HTML binding
$(element).append(result); // "result" should be a binding, basically
}
});
// detailed more in the jsFiddle
},
refresh: function() {
// detailed more in the jsFiddle
},
change: function() {
// detailed more in the jsFiddle
}
});
});
I realize that I could just write out the HTML, but that would not perform the actual "binding" for kendo to track it.
I'm not really sure what you are attempting to do, but it seemed to me that the custom "repeat" binding was unnecessary. Here's what I came up with. Is this on track with what you are trying to do?
Here is a working jsFiddle example.
HTML
<div id="example">
<div data-template="display-associative-many" data-bind="source: Root.Items"></div>
</div>
<script type="text/x-kendo-template" id="display-associative-many">
#for (var prop in data) {#
# if (data.hasOwnProperty(prop)) {#
# if (data[prop].Id) {#
<div><span>${data[prop].Id}</span> : <span>${data[prop].Name}</span></div>
# }#
# }#
#}#
</script>
JavaScript
$(function () {
var input = {
"One" : { Name: "One", Id: "id/one" },
"Two" : { Name: "Two", Id: "id/two" },
"Three" : { Name: "Three", Id: "id/three" }
};
var viewModel = new kendo.data.ObservableObject({
Id: "test/id",
Root: {
Items: input
}
});
kendo.bind('#example', viewModel);
});

Backbone.js Collection's fetch call is erroring out

Still wrapping my head around Backbone, and running into an issue where my Collection won't populate when I'm passing it JSON from a file. The fetch() call is erroring out, but I'm not sure how to debug it exactly, as my console.log()'s aren't telling me anything useful (as far as I know how to dig through them).
Here's the code:
ItemGroup = Backbone.Collection.extend({
model: Item, // left out definition since it's very simple
url: 'js/items.json',
initialize: function(models, options) {
this._meta = {};
},
parse: function(response) { // parse is not being called, not sure why?
this.set(response.name, 'name');
return response.items;
},
set: function(val, prop) {
this._meta[prop] = val;
},
get: function(prop) {
return this._meta[prop];
}
});
ItemGroupView = Backbone.View.extend({
el: '#item-container',
initialize: function(options) {
this.collection.bind('reset', this.render, this);
this.collection.fetch({
success : function() {
alert('successful');
},
error : function(collection, xhr, options) { // This is being triggered, not sure why?
console.log(collection);
console.log(xhr);
console.log(options);
}
});
},
processItem: function(item) {
var itemView = new ItemView({ model: item });
this.$el.append(itemView.render().el);
},
render: function() {
console.log(this.collection); // this shows an empty collection
var itemGroupHtml = this.template({ name: this.collection.get('name') });
$(this.main).html(itemGroupHtml);
_.each(this.collection.models, this.processItem, this);
return this;
}
});
var toiletryItems = new ItemGroup();
var toiletryGroupView = new ItemGroupView({ collection: toiletryItems });
And here's my json (I can see that's it's successfully finding the file, since I see it as a 200 in the network requests using the Chome inspector):
[
{
'name' : 'toiletries',
'items' : [
{ 'name': 'toothbrush' },
{ 'name': 'deodorant' },
{ 'name': 'toothpaste' },
]
}
]
Thanks in advance!
UPDATE:
Fixed the invalid json, but still seeing an empty toiletryItems collection. Any ideas?
Discovered the problem was with my parse function. The response param is an array, and so that function should be:
parse: function(response) { // parse is not being called, not sure why?
this.set(response[0].name, 'name');
return response[0].items;
},

backbone.js collection usage

I'm running into a problem maintaining my collection. First, I load attendees into a collection via fetch. This loads existing attendees from the database in to the collection. I also have a button which allows a user to add new attendees. When an attendee is manually entered it seems to wipe out the models loaded into the collection via fetch and starts fresh. All manually added attendees now populate the collection; however, i would like both the fetch loaded and manually added attendees to populate this list.
var InviteeView = Backbone.View.extend({
tagName: "tr",
initialize: function() {
this.collection = new InviteeJSONList();
_.bindAll(this, 'render','appendItem','remove','saveInvitee');
},
events: {
"click .removeInvitee":"remove",
"click .saveInvitee":"saveInvitee"
},
render: function() {
var source = $("#invitee-template").html();
var template = Handlebars.compile(source);
var context = inviteeListJSON.attributes['json'];
var html=template(context);
$(this.el).html(html);
return this;
},
appendItem: function() {
$("#attendees").append(this.render().el);
},
remove: function() {
$(this.el).remove();
},
saveInvitee: function() {
var value = $(this.el).find('select').val();
var model = this.collection.attributes['json']['invitees'];
model = model.filter(function(attributes) {return attributes.encrypted_id==value});
var attendee = new Attendee({
user_id: model[0]['id'],
meeting_id: '<?=$mid?>',
status: 'Uncomfirmed',
first_name: model[0]['first_name'],
last_name: model[0]['last_name'],
email: model[0]['email'],
user_uuid: model[0]['encrypted_id'],
unavailable_dates: model[0]['unavailable_dates']
});
attendeeView.addAttendeeItem(attendee.attributes)
this.remove();
}
});
var AttendeeList = Backbone.Collection.extend({
model: Attendee,
url: '<?=$baseURL?>api/index.php/attendees/<?=$mid?>&timestamp=<?=$timestamp?>&userid=<?=$userid?>&apikey=<?=$apikey?>',
parse: function(response) {
if(response!="No History") {
$.each(response['attendees'], function(key, value) {
attendeeView.addAttendeeItem(value);
});
$('.loading_attendees').hide();
}
else {
$('.loading_attendees').html("No attendees exists for this meeting.");
}
}
});
var AttendeeView = Backbone.View.extend({
el: $('body'),
initialize: function() {
_.bindAll(this, 'render','fetchAttendees', 'appendItem', 'addAttendeeItem');
this.counter=0;
this.collection = new AttendeeList();
this.collection.bind('add', this.appendItem);
this.fetchAttendees();
},
events: {
"click #addInvitee":"appendInvitees",
},
appendInvitees: function() {
var inviteeView = new InviteeView();
inviteeView.appendItem();
},
render: function() {
},
fetchAttendees: function() {
this.collection.fetch({
success: function(model, response) {
},
error: function(model, response) {
$('#loading_attendees').html("An error has occurred.");
}
});
},
appendItem: function(item) {
var attendeeItemView = new AttendeeItemView({
model: item
});
$("#attendees").append(attendeeItemView.render().el);
attendeeItemView.updateAttendeeStatusSelect();
},
addAttendeeItem: function(data) {
this.counter++;
var attendee = new Attendee({
id: data['id'],
user_id: data['user_id'],
meeting_id: data['id'],
status: data['status'],
comments: data['comments'],
attended: data['datetime'],
first_name: data['first_name'],
last_name: data['last_name'],
email: data['email'],
counter: this.counter,
user_uuid: data['user_uuid'],
unavailable_dates: data['unavailable_dates']
});
this.collection.add(attendee);
},
});
After the collection (2 items loaded from REST API) is loaded via fetch():
console.log(this.collection.models) outputs:
[d]
[d,d]
Then when I manually add an attendee via a button the collection seems to reset:
console.log(this.collection.models) outputs:
[d]
Good that it's working, as there are many ways to go. I probably would have structured it a bit differently to leverage the Backbone methods that instantiate modes, but working code is the real goal, so these are just my thoughts:
Rather than actually instantiate the Models in the Collection parse() method, merely have parse return an array of data objects from which Backbone would instantiate the models, and trigger a
Rather than call fetch for the Collection inside AttendeeView, but outside the View class
Either have AttendeeView represent the view for a single attendee, or name it AttendeeListView and have it render the list
For instance:
AttendeeList = Backbone.Collection.extend({
...
parse: function(response) {
// create an array of objects from which the models can be parsed
var rawItems = [];
$.each(response['attendees'], function(key, value) {
rawItems.push({
id: data['id'],
user_id: data['user_id'],
meeting_id: data['id'],
status: data['status'],
comments: data['comments'],
attended: data['datetime'],
first_name: data['first_name'],
last_name: data['last_name'],
email: data['email'],
counter: this.counter,
user_uuid: data['user_uuid'],
unavailable_dates: data['unavailable_dates']
});
});
return rawItems;
},
...
}
and then either use the success/failure call backs:
AttendeeList.fetch( onListFetchSuccess , onListFetchFail );
or listen for the reset event that gets triggered:
AttendeeList.on('reset', createAttendeeListView );
(I didn't actually edit and run the code, this is just an outline)
I ended up resolving the issue by removing the url parameter and parse function out of the collection and into the view. Now everything works as expected.

Categories

Resources