Trouble with Knockout Mapping Create/Update - javascript

I am trying to map data so that elements only get re-rendered when values have actually changed.
{
Apps : [
{
"Categories" : [{
"Name" : "#Some,#More,#Tags,#For,#Measure"
}
],
"Concentrator" : "",
"Health" : 1,
"Id" : 2648,
"Ip" : "1.1.1.1",
"IsDisabled" : true,
"IsObsolete" : false,
"Name" : "",
"Path" : "...",
"SvcUrl" : "http://1.1.1.1",
"TimeStamp" : "\/Date(1463015444163)\/",
"Type" : "...",
"Version" : "1.0.0.0"
}
...
]
...
}
var ViewModel = function() {
self.Apps = ko.observableArray([]);
}
var myModel = new ViewModel();
var map = {
'Apps': {
create: function (options) {
return new AppModel(options.data);
},
key: function(data) { return ko.utils.unwrapObservable(data.Id); }
}
}
var AppModel = function(data){
data.Categories = data.Categories[0].Name.split(',');
ko.mapping.fromJS(data, { }, this);
return this;
}
function UpdateViewModel() {
return api.getDashboard().done(function (data) {
ko.mapping.fromJS(data, map, myModel);
});
}
loopMe(UpdateViewModel, 5000);
function loopMe(func, time) {
//Immediate run, once finished we set a timeout and run loopMe again
func().always(function () {
setTimeout(function () { loopMe(func, time); }, time);
});
}
<script type="tmpl" id="App-template">
<div>
<!-- ko foreach: Categories -->
<span class="btn btn-default btn-xs" data-bind="text:$data"></span>
<!-- /ko -->
</div>
</script>
On the first run of UpdateViewModel I will see 5 spans as expected. On the second call, receiving the same data, it gets updated to a single span that says [Object object] which is because it still thinks Categories is an array of objects instead of an array of strings.
Everything seems fixed if I change 'create' to 'update' in my map, however it seems that the spans are then re-rendered every time regardless if data changed or not.
Can anyone lend me a hand in the direction I need to go so that I can
adjust the Categories array from objects to strings
Only re-render/render changed/new items
Here is a Fiddle showing the behavior

The problem is with these lines:
var AppModel = function(data){
data.Categories = data.Categories[0].Name.split(','); // <-- mainly this one
ko.mapping.fromJS(data, { }, this);
return this;
}
There's two problems:
You mutate the data object which (at least in our repro) mutates the original object that data references to. So first time one of the fakeData objects is passed in, that one is mutated in place, and will forever be "fixed".
You mutate it in the AppModel constructor function, which is only called the first time. According to your key function, the second time the constructor should not be called, but instead ko-mapping should leave the original object and mutate it in place. But it will do so with a "wrongly" formatted data.Categories property.
The correct fix seems to me to be in your data layer, which we have mocked in the repro, so it makes little sense for my answer to show you how.
Another more hacky way to do this would be to have an update method in your mapping like so:
update: function(options) {
if (!!options.data.Categories[0].Name) {
options.data.Categories = options.data.Categories[0].Name.split(',');
}
return options.data;
},
When it encounters an "unmodified" data object it'll do the same mutation. See this jsfiddle for that solution in action.

Related

Zingchart Live Feed View Change

Let me start off by saying I am fairly new to this.
So what I'm currently doing is I'm playing around with the live feed chart using a js function that produces and stringifies random numbers.
window.feed = function(callback) {
var tick = {};
tick.plot0 = parseInt(10+900*Math.random(), 10);
callback(JSON.stringify(tick));
};
The first issue I'm trying to tackle is being able to switch charts with the click of a button without the feed restarting, essentially having the feed function running in the back and (I'd assume) storing the data into an array? Would that be the correct approach? But currently, when I click the button it just restarts the feed. Here's the code:
$('#chartButton').bind('click', function(){
zingchart.exec('chart', 'setdata',{
'data': {
'type': 'bar',
"refresh":{
"type":"feed",
"transport":"js",
"url":"feed()",
"interval":200
},
'series':[
{
'values':[]
//[11,26,7,44,11]
},
{
'values':[]
//[42,13,21,15,33]
}
]
}
});
});
$('#lineButton').bind('click', function(){
zingchart.exec('chart', 'setdata',{
'data': {
'type': 'line',
"refresh":{
"type":"feed",
"transport":"js",
"url":"feed()",
"interval":200
},
'series':[
{
'values':[]
// [11,26,7,44,11]
},
{
'values':[]
// [42,13,21,15,33]
}
]
}
});
});
$('#areaButton').bind('click', function(){
zingchart.exec('chart', 'setdata',{
'data': {
'type': 'area',
"refresh":{
"type":"feed",
"transport":"js",
"url":"feed()",
"interval":200
},
'series':[
{
'values':[]
// [11,26,7,44,11]
},
{
'values':[]
// [42,13,21,15,33]
}
]
}
});
});
And lastly, I'm trying to make it so it has two different "values" being displayed on the chart, but I can't seem to figure out how I would do that. The tutorial says if you're going to use two values inputs create the objects, but doesn't extrapolate on how to get the different values transmuted.
My hunch is that I create the feed function, but store all the values being created into an array, one for each function. Then assign those arrays to be the values of the chart, but I've been having trouble figuring out exactly how to increment through an array in javascript so you can keep adding more and more data to it as it is created. Any help would be much appreciated.

Knockout JS not setting all members observable

What I am trying to do is to get data from the server and then putting it all in an observable and then make all the properties observable. The issue I am facing is that it does not make all my properties observable and I need them all to be observable as sometimes depending on the data it makes some properties observable and sometimes it doesn't.
var viewModel = this;
viewModel.Model = ko.observable();
viewModel.SetModel = function (data) {
viewModel.Model(ko.mapping.fromJS(data));
}
The data that I am receiving from the server is like this for example: normaldata,items(this is an array with unknown number of elements).
so if i try to access data like viewModel.Model().Items[0]().Layer() i sometimes have Layer as a function and sometimes it is a normal element with observable elements.I want all my objects inside Items to have Layer as a function.
Server data example:
Name: "test"
Items: [Layer[ID: 132]]
In this example Name,Items and ID are observable but Layer is not.
Fiddle example:
jsfiddle.net/98dv11yz/3
So the problem is that sometimes the layer is null resulting in ko making the property observable but sometimes that property has id and ko makes only the child elements observable. The problem is that i have if's in the code and i want it to be a function so i can always reffer to it as layer() because now it is sometimes layer or layer()
An explenation for what's happening:
When the ko.mapping plugin encounters an object in your input, it will make the object's properties observable, not the property itself.
For example:
var myVM = ko.mapping.fromJS({
name: "Foo",
myObject: {
bar: "Baz"
}
});
Will boil down to:
var myVM = {
name: ko.observable("Foo"),
myObject: {
bar: ko.observable("Baz")
}
}
and not to:
var myVM = {
name: ko.observable("Foo"),
myObject: ko.observable({
bar: ko.observable("Baz")
})
}
The issue with your data structure is that myObject will sometimes be null, and sometimes be an object. The first will be treated just as the name property in this example, the latter will be treated as the myObject prop.
My suggestion:
Firstly: I'd suggest to only use the ko.mapping.fromJS method if you have a well documented and uniform data structure, and not on large data sets that have many levels and complexity. Sometimes, it's easier to create slim viewmodels that have their own mapping logic in their constructor.
If you do not wish to alter your data structure and want to keep using ko.mapping, this part will have to be changed client-side:
Items: [
{ layer: {id: "0.2"} },
{ layer: null}
]
You'll have to decide what you want to achieve. Should the viewmodel strip out the item with a null layer? Or do you want to render it and be able to update it? Here's an example of how to "correct" your data before creating a view model:
var serverData = {
Name: "Example Name",
Id: "0",
Items: [
{layer: {id: "0.2"} },
{layer: null}
]
};
var correctedData = (function() {
var copy = JSON.parse(JSON.stringify(serverData));
// If you want to be able to render the null item:
copy.Items = copy.Items.map(function(item) {
return item.layer ? item : { layer: { id: "unknown" } };
});
// If you don't want it in there:
copy.Items = copy.Items.filter(function(item) {
return item.layer;
});
return copy;
}());
Whether this solution is acceptable kind of relies on how much more complicated your real-life use will be. If there's more complexity and interactivity to the data, I'd suggest mapping the items to their own viewmodels that deal with missing properties and what not...

Populate Backbone.js JSON response into nested collections inside nested collections/models

My problem is that I am just starting out with Backbone.js and are having trouble wrapping my head around a complex problem. I want to save a form that have infinite fields, and some of the fields also needs to have infinite options. I'm just worried I might have started at the wrong end with a JSON response, instead of building the models/collections first. Here is a short pseudocode of what I try to achieve.
id:
parent: <blockid>
fields: array(
id:
title:
helpertext
options: array(
id:
type:
value:
)
)
Currently I am working with a faked JSON response from the server, which I built from scratch, and now I want to divide it into models and collections on the client side.
//Fake a server response
var JSONresponse = {
"formid":"1",
"fields":[
{
"fieldid":"1",
"title":"Empty title",
"helper":"Helper text",
"type":"radio",
"options":[
{
"optionid":"1",
"value":"Empty option.."
},
{
"optionid":"2",
"value":"Empty option.."
}
]
},
{
// fieldid2
}
]
};
The idea is to add fields as I see fit, and then if the field type is radio/checkbox/ul/ol there must also be an "options" array within the field.
My work so far:
var app = {};
app.Models = {};
app.Collections = {};
app.View = {};
app.Models.Option = Backbone.Model.extend({
});
app.Collections.Options = Backbone.Collection.extend({
model: app.Models.Option
});
app.Models.Field = Backbone.Model.extend({
options: new app.Collections.Options()
});
app.Collections.Fields = Backbone.Collection.extend({
model: app.Models.Field
});
app.Models.Form = Backbone.Model.extend({
formid : "1",
fields: new app.Collections.Fields(),
initialize: function() {
}
});
How do I split up my JSON response into all these models and collections?
(Perhaps I should re-evaluate my approach, and go for something like form.fieldList and form.optionList[fieldListId] instead. If so, how would that look like?)
Edit: Here is a little jsfiddle after many fixes, but I still don't really know how to make the inner options list work.
The easiest solution would be using Backbone Relational or Backbone Associations.
The documentation should be enough to help you get started.
If you don't want to use a library you could override the parse function on the Form model.
app.Models.Form = Backbone.Model.extend({
defaults: {
fields: new app.Collections.Fields()
},
parse: function(response, options) {
return {
formid: response.formid,
fields: new app.Collections.Fields(_.map(response.fields, function(field) {
if (field.options) {
field.options = new app.Collections.Options(field.options);
}
return field;
}))
};
}
});
Now if you fetch a form from the server, the response will be parsed into an object graph of models and collections.
form.get('fields') will return an app.Collections.Fields collection. form.get('fields').first().get('options') will return an app.Collections.Options collection, if any options exist.
Also, you could create the form model like this:
var form = new app.Models.Form(JSONresponse, {
parse: true
});
This would result in the same object structure.
It's quite hard to handle the case of nested models and collections right in plain Backbone.
Easiest way of handling this will be something like this:
var Option = Nested.Model.extend({
idAttribute : 'optionid',
defaults : {
optionid : Integer
value : ""
}
});
var Field = Nested.Model.extend({
idAttribute : 'fieldid',
defaults : {
fieldid : Integer,
title : "",
helper : "",
type : "radio",
options : Option.Collection
}
});
var Form = Nested.Model.extend({
idAttribute : 'formid',
defaults : {
formid: Integer,
fields: Field.Collection
});
https://github.com/Volicon/backbone.nestedTypes
And that's it. Yep, you'll get direct access to the attributes as free bonus, just form.fields.first().options.first().value, without that get and set garbage.

Ember computed property not being updated

I'm not too entirely sure why my computed property isn't returning updated values.
I have a list of options that a user can click through, and the action updates a property, which is an Ember Object, for the controller. I have a computed property that loops through the object, looks for keys that have non-null values for that Ember Object property, and if it does find one, returns false, otherwise true.
Here's the stuff:
App.SimpleSearch = Ember.Object.extend({
init: function() {
this._super();
this.selectedOptions = Ember.Object.create({
"Application" : null,
"Installation" : null,
"Certification" : null,
"Recessed Mount" : null,
"Width" : null,
"Height" : null,
"Heating" : null,
"Power" : null
});
},
selectedOptions: {},
numOfOptions: 0,
allOptionsSelected: function() {
var selectedOptions = this.get('selectedOptions');
for (var option in selectedOptions) {
console.log(selectedOptions.hasOwnProperty(option));
console.log(selectedOptions[option] === null);
if (selectedOptions.hasOwnProperty(option)
&& selectedOptions[option] === null) return false;
}
return true;
}.property('selectedOptions')
});
App.SimpleSearchRoute = Ember.Route.extend({
model: function() {
return App.SimpleSearch.create({
'SimpleSearchOptions': App.SimpleSearchOptions,
'numOfOptions': App.SimpleSearchOptions.length
});
},
setupController: function(controller, model) {
controller.set('model', model);
}
});
App.SimpleSearchController = Ember.ObjectController.extend({
getProductsResult: function() {
var productsFromQuery;
return productsFromQuery;
},
setSelection: function (option, selectionValue) {
this.get('selectedOptions').set(option, selectionValue);
this.notifyPropertyChange('allOptionsSelected');
},
actions: {
registerSelection: function(option) {
console.log('registering selection');
console.log(this.get('allOptionsSelected'));
console.log(this.get('selectedOptions'));
this.setSelection(option.qname, option.value);
},
The action in the controller, registerSelection is firing just fine, but I only see the console.log from the SimpleSearch model once. Once the property is computed that first time, it isn't paid attention to after that, which means that the computed property isn't observing the changes to selectedOptions whenever this is called:
setSelection: function (option, selectionValue) {
this.get('selectedOptions').set(option, selectionValue);
this.notifyPropertyChange('allOptionsSelected');
},
Edit:
I actually solved my issue without changing anything.
I've changed the following line:
this.notifyPropertyChange('allOptionsSelected');
to:
this.get('model').notifyPropertyChange('selectedOptions');
notifyPropertyChange needs to be called within the context of the model (or the Ember Object that has observers of a specific property), and the string sent as an argument is the name of the property that was updated.
After I made that change, it worked as intended.
Ember doesn't observe objects for any change on the object, it observes a single property.
How is this affecting you? Well in this method you are watching selectedOptions, but that object itself is still the same object, you might be changing properties on it, but not the object itself. And then you are telling Ember in the scope of the controller that allOptionsSelected has changed, so it regrabs it, but it doesn't recalculate it because it's not dirty, it just changed. You'd really want to say selectedOptions has changed to get allOptionsSelected to recalculate its value. Unfortunately you're doing this in the scope of the controller, so telling the controller that property has changed doesn't matter to it.
allOptionsSelected: function() {
var selectedOptions = this.get('selectedOptions');
for (var option in selectedOptions) {
console.log(selectedOptions.hasOwnProperty(option));
console.log(selectedOptions[option] === null);
if (selectedOptions.hasOwnProperty(option)
&& selectedOptions[option] === null) return false;
}
return true;
}.property('selectedOptions')
Here's a dummy example showing what things cause it to actually update.
http://emberjs.jsbin.com/iCoRUqoB/1/edit
Honestly since you're not watching particular properties I'd probably do an array, or create a method on the object that handles adding/removing/modifying the properties so you could fire from within it's scope a property change updating all parent listeners with the changes.
Ember computed property dependent keys can be a
property key. in example: 'jobTitle'
computed property key. in example: 'companyName'
property key of an object. in example:
'salesAccount.name and salesAccount.website'
Example extracted from Ember.model definition:
...
jobTitle : DS.attr('string'),
salesAccount: belongsTo('salesAccount'),
companyName: Ember.computed('jobTitle', 'salesAccount.name', {
get: function () {
return this.get('salesAccount.name');
}
}),
companyWebsite: Ember.computed('salesAccount.website', 'companyName', {
get: function () {
return this.get('salesAccount.website');
}
})
...

backbone-relational .set() method not updating related models

I've got backbone-relational working fairly well so far. I have relationships and reverse relationships well established (see below). When I initially call .fetch() on my Country model instance, the nominees array is parsed out into nominee models perfectly.
When I call .fetch() again later, however, these related models do not update, even though the nominee data has changed (e.g. the vote count has incremented). Essentially it seems that Backbone's .set() method understands relationships initially but not subsequently.
Country Model
var Country = Backbone.RelationalModel.extend({
baseUrl : config.service.url + '/country',
url : function () {
return this.baseUrl;
},
relations : [
{
type : Backbone.HasMany,
key : 'nominees',
relatedModel : Nominee,
collectionType : Nominee_Collection,
reverseRelation : {
key : 'country',
includeInJSON : false
}
}
]
});
JSON Response on country.fetch()
{
"entrant_count" : 1234,
"vote_count" : 1234,
"nominees" : [
{
"id" : 3,
"name" : "John Doe",
"vote_count" : 1,
"user_can_vote" : true
},
{
"id" : 4,
"name" : "Marty McFly",
"vote_count" : 2,
"user_can_vote" : true
}
]
}
Any help would be greatly appreciated, as always.
So it appears that backbone-relational specifically forgoes updating relations automatically (see the updateRelations method), and simply emits a relational:change:nominees event which your models can target. If, however, you wish to programmatically update your related models, simply modify the updateRelations method as follows:
Backbone.RelationalModel.prototype.updateRelations = function( options ) {
if ( this._isInitialized && !this.isLocked() ) {
_.each( this._relations || [], function( rel ) {
// Update from data in `rel.keySource` if set, or `rel.key` otherwise
var val = this.attributes[ rel.keySource ] || this.attributes[ rel.key ];
if ( rel.related !== val ) {
this.trigger( 'relational:change:' + rel.key, this, val, options || {} );
// automatically update related models
_.each(val, function (data) {
var model = rel.related.get(data.id);
if (model) {
model.set(data);
} else {
rel.related.add(data);
}
});
}
}, this );
}
};
(Note that this does not handle deletion of models from a collection, only updates to existing models, and the addition of new models to a collection)

Categories