Knockout.js observable binding not updating (with JSON mapping)? - javascript

Background: I've got a single-page knockout.js app using the mapping plugin. The data is updated via Websocket JSON from the server. I can see that the app is successfully receiving the data (printing data in console) and when there are object removals/additions, the ViewModel updates no problem.
Problem: When a property of an object is updated from the server, it does not change the ViewModel. Do I need to return the object property somehow with each update?
Here are the relevant snippets of code:
var userMapping = {
"users": {
key: function(data) { return ko.utils.unwrapObservable(data.id); },
create: function(options) {
// for sortable ui access
return createUser(options.data);
}
}
};
var jobMapping = {
"jobs": {
key: function(data) { return ko.utils.unwrapObservable(data.id); },
create: function(options) {
// for sortable ui access
return createJob(options.data);
},
update: function(options) {
return createJob(options.data);
}
}
};
var createJob = function(job, user) {
// leaflet init
createJobIcon(job);
// general data mapping
var result = ko.mapping.fromJS(job);
return result;
};
self.engineModel.update = function(data) {
ko.mapping.fromJS(data, userMapping, self.engineModel);
};
And in the ViewModel:
<li data-bind="visible: canceled()==false, attr: {class: 'job-li canceled-'+canceled()+' started-'+started()+' hold-'+hold() }">
Thanks for the insight!

I've been able to fix the behaviour but I remain skeptical about the long-term impact from the decision.
I removed this line:
key: function(data) { return ko.utils.unwrapObservable(data.id); },
Now everything updates as it should. If anyone has thoughts about further processing I'm all ears (for example, does this affect performance?)

Related

Backbone js building a collection from the results returned from multiple URL's

I have a model that looks like this:
var BasicModel = Backbone.Model.extend({
defaults: {
a: '',
b: '',
c: '',
d: '',
e: ''
},
idAttribute: "f",
parse: function (data) {
return data;
},
initialize: function () {
console.log('Intialized');
},
constructor: function (attributes, options) {
Backbone.Model.apply(this, arguments);
}
});
Collections like this:
var BasicCollection = Backbone.Collection.extend({
model: BasicModel,
url: urlCode
});
var ACollection = BasicCollection.extend({
parse: function (data) {
return data.a.b.c.d;
}
});
var aCollection = new ACollection ();
And Views like this:
var BasicView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#basic-status-template').html()),
render: function () {
this.$el.html(this.template(this.model.attributes));
return this;
}
});
var BasicsView = Backbone.View.extend({
initialize: function () {
this.render();
},
});
This is how the collection fetch looks (Which builds the views):
aCollection.fetch({
success: function () {
// View
var aView = BasicsView.extend({
el: '#foobar #table-body',
render: function () {
this.$el.html('');
aCollection.each(function (model) {
var x = new BasicView({
model: model
});
this.$el.append(x.render().el);
}.bind(this));
return this;
}
});
var app = new aView();
}
});
But now I face a problem when trying to add another piece of detail to the tables that the views will populate. One of the columns will require data that will come from a seperate url. But I still want it to be part of the same process.
Is there are way to form a collection from the result of two URL's. (i.e. a, b, d and e come from URL 1, and c comes from URL 2)?
This way all I would need to change was the template and it should all work the same. Instead of having to alter a load of other stuff as well.
Thanks.
You have few options:
Update the endpoint to send required data. This is the proper way to do it. Collection should Ideally have single endpoint
Send a seperate AJAX request to get data from one URL before fetching collection, then in collection's parse method add the data to the response fetched from collection's URL
Do something like:
$.when(collection.fetch(), collection.fetchExtraData())
.done(()=> { /* create view here */ });
fetchExtraData here is a custom function that sends extra request and updates collection properly with the data. This way both requests are sent simultaneously. You need to make sure parse doesn't reset the data from other endpoint.

React Component JSON Callback Scope

I'm using generator-react-webpack to create a React web app. This web app relies on JSON feeds - one of which is hosted on a CDN that does not support JSONP and the CDN url is a subdomain of the webapp. Is there any way to return the JSON data from within the React Component?
Basic React Component:
var AppComponent = React.createClass({
loadData: function() {
jQuery.getJSON(jsonFile.json?callback=?)
.done(function(data) {
console.log(data);
}.bind(this));
},
render: function(){
return ( ... );
}
});
I've tried a few solutions, and have come to the conclusion that I need to define my own callback on the JSON file like so:
JSON:
handleData({
"data": "hello World"
})
Is there a way for the handleData callback to be defined in the react component, or the response accessed from the react component? Any thoughts as to how I can get this to work are much appreciated. Thanks!
This looks like an odd way to do things, especially the part where you're using jQuery. That's a client-side utility to overcome not knowing where everything is and not having direct access to your elements. It makes no sense to use it when you're using React weith Webpack for bundling: React already knows where everything is (using refs) and Webpack means you can just use regular universal Node modules for everything that you need to do.
I'd recommend using something like, using request or a similar universal fetch API:
// loadData.js
var request = require('request');
var loadData = function(urlYouNeed, handler) {
request(urlYouNeed, function(error, response, body) {
if (error) {
return handler(error, false);
}
// do anything processing you need on the body,
var data = process(body);
handler(false, data);
};
So: just a module you can require in any component you define with require('./loadData'). And then in your actual component you do this:
var loadData = require('./loadData');
var AppComponent = React.createClass({
getDefaultProps: function() {
return {
jsonURL: "cdn://whateverjson.json"
};
},
getInitialState: function() {
loadData(this.props.jsonURL, this.updateData);
return {
data: []
}
},
updateData: function(err, data) {
if (err) {
return console.error(err);
}
data = secondaryEnsureRightFormat(data);
this.setState({ data: data });
},
render: function(){
var actualThings = this.state.data.map((entry, pos) => {
return <Whatever content={entry} key={entry.dontUseThePosVariableUpThere}/>
});
return (
<div>
...
{actualThings}
...
</div>
);
}
});
Much cleaner.
If I understand correctly the question, you only have to change your loadData this way :
loadData: function() {
var c = this
jQuery.getJSON(jsonFile.json?callback=?)
.done(function(data) {
c.handleData(data)
});
},
handleData: function(data) {
/* Implement here the function to handle the data */
},

Backbone collection reset and parse

I am rendering a view in my backbone application when a collection is reset,
initialize: function(options) {
this.options = options;
this.model.get('projects').fetch({
data: {
organisation_id: this.model.get('id')
}
}, {reset:true});
this.model.get('projects').on('reset', this.render, this);
this.model.get('projects').on('add', this.addNewProject, this);
this.model.get('projects').on('sort', this.addProjects, this);
},
render: function() {
console.log(this.model.get('projects').state);
this.$el.html( this.template({
is_owner: this.options.is_owner,
className: this.options.className,
pagination: this.model.get('projects').state
}));
this.addProjects();
this.filter = new Pops.Views.OrganisationProjectsFilter({
el:this.$el.find('.div-organisation-filter-wrapper'),
model : this.model,
collection: this.collection
});
this.filter.render().el;
return this;
},
As you can see I run a fetch and the reset my collection to the fetched data. My problem is that in the view I am trying to use some values that come from the server, and it appears they are null, here is my collection,
App.Collections.PaginatedProjects=
Backbone.PageableCollection.extend({
url: App.API_ROOT + "/projects/paginated",
// Initial pagination states
state: {
pageSize: 2,
sortKey: "name",
order: 1,
totalRecords:null
},
// You can remap the query parameters from `state` keys from
// the default to those your server supports
queryParams: {
totalPages: null,
totalRecords: null,
sortKey: "sort",
},
// get the state from Github's search API result
parseState: function (resp, queryParams, state, options) {
this.state.totalRecords = resp.total;
this.state.totalPages = resp.total / this.state.pageSize;
this.state.lastPage = this.state.totalPages;
},
// get the actual records
parseRecords: function (resp, options) {
return resp.data;
}
});
As you can see I am running the parse functions to retrieve and set to values, if I console my collection I can see the correct values, but when I try and use them in my view they are null, am I using parse or reset wrong or maybe both?
I think this is because when you render the data didn't arrive yet. Try this:
this.model.get('projects').fetch({
success: function(model,response) {
var data = //some of your answer
}
});
From what I understand, you did a
console.log(this.model.get('projects').state);
and found out it is print out correctly but then used in the
this.template({
is_owner: this.options.is_owner,
className: this.options.className,
pagination: this.model.get('projects').state
})
then it does not appear? If this is the case, I don't think it's a problem in Backbone Collection. I think it has something to do with how you access the data in your template.
If you are using handlebars, because this "state" variable is a json,
you maybe using
{{pagination.pageSize}}
in the hbs file to print it out. I have a heizy memory that it was not supported a while ago. try using
{{pagination/pageSize}}
Also, if this snippet is inside a {{#if}} or a {{#each}} etc, according to the handlebars documentation, you may need to go in a scope. use
{{../pagination/pageSize}} or {{../../pagination/pageSize}}
I ran into the problem a while ago and did a lot of search to found out about this. Hope it helps

Ember Data belongsTo async relationship omitted from createRecord() save() serialization

Edit 11/16/14: Version Information
DEBUG: Ember : 1.7.0 ember-1.7.0.js:14463
DEBUG: Ember Data : 1.0.0-beta.10+canary.30d6bf849b ember-1.7.0.js:14463
DEBUG: Handlebars : 1.1.2 ember-1.7.0.js:14463
DEBUG: jQuery : 1.10.2
I'm beating my head against a wall trying to do something that I think should be fairly straightforward with ember and ember-data, but I haven't had any luck so far.
Essentially, I want to use server data to populate a <select> dropdown menu. When the form is submitted, a model should be created based on the data the user chooses to select. The model is then saved with ember data and forwarded to the server with the following format:
{
"File": {
"fileName":"the_name.txt",
"filePath":"/the/path",
"typeId": 13,
"versionId": 2
}
}
The problem is, the typeId and versionId are left out when the model relationship is defined as async like so:
App.File = DS.Model.extend({
type: DS.belongsTo('type', {async: true}),
version: DS.belongsTo('version', {async: true}),
fileName: DS.attr('string'),
filePath: DS.attr('string')
});
The part that is confusing me, and probably where my mistakes lie, is the controller:
App.FilesNewController = Ember.ObjectController.extend({
needs: ['files'],
uploadError: false,
// These properties will be given by the binding in the view to the
//<select> inputs.
selectedType: null,
selectedVersion: null,
files: Ember.computed.alias('controllers.files'),
actions: {
createFile: function() {
this.createFileHelper();
}
},
createFileHelper: function() {
var selectedType = this.get('selectedType');
var selectedVersion = this.get('selectedVersion');
var file = this.store.createRecord('file', {
fileName: 'the_name.txt',
filePath: '/the/path'
});
var gotDependencies = function(values) {
//////////////////////////////////////
// This only works when async: false
file.set('type', values[0])
.set('version', values[1]);
//////////////////////////////////////
var onSuccess = function() {
this.transitionToRoute('files');
}.bind(this);
var onFail = function() {
this.set('uploadError', true);
}.bind(this);
file.save().then(onSuccess, onFail);
}.bind(this);
Ember.RSVP.all([
selectedType,
selectedVersion
]).then(gotDependencies);
}
});
When async is set to false, ember handles createRecord().save() POST requests correctly.
When async is true, ember handles GET requests perfectly with multiple requests, but does NOT add the belongsTo relationships to the file JSON during createRecord().save(). Only the basic properties are serialized:
{"File":{"fileName":"the_name.txt","filePath":"/the/path"}}
I realize this question has been asked before but I have not found a satisfactory answer thus far and I have not found anything that suits my needs. So, how do I get the belongsTo relationship to serialize properly?
Just to be sure that everything is here, I will add the custom serialization I have so far:
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.capitalize(type.typeKey);
data[root] = this.serialize(record, options);
},
keyForRelationship: function(key, type){
if (type === 'belongsTo') {
key += "Id";
}
if (type === 'hasMany') {
key += "Ids";
}
return key;
}
});
App.FileSerializer = App.ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
type: { serialize: 'id' },
version: { serialize: 'id' }
}
});
And a select:
{{ view Ember.Select
contentBinding="controller.files.versions"
optionValuePath="content"
optionLabelPath="content.versionStr"
valueBinding="controller.selectedVersion"
id="selectVersion"
classNames="form-control"
prompt="-- Select Version --"}}
If necessary I will append the other routes and controllers (FilesRoute, FilesController, VersionsRoute, TypesRoute)
EDIT 11/16/14
I have a working solution (hack?) that I found based on information in two relevant threads:
1) How should async belongsTo relationships be serialized?
2) Does async belongsTo support related model assignment?
Essentially, all I had to do was move the Ember.RSVP.all() to after a get() on the properties:
createFileHelper: function() {
var selectedType = this.get('selectedType');
var selectedVersion = this.get('selectedVersion');
var file = this.store.createRecord('file', {
fileName: 'the_name.txt',
filePath: '/the/path',
type: null,
version: null
});
file.set('type', values[0])
.set('version', values[1]);
Ember.RSVP.all([
file.get('type'),
file.get('version')
]).then(function(values) {
var onSuccess = function() {
this.transitionToRoute('files');
}.bind(this);
var onFail = function() {
alert("failure");
this.set('uploadError', true);
}.bind(this);
file.save().then(onSuccess, onFail);
}.bind(this));
}
So I needed to get() the properties that were belongsTo relationships before I save the model. I don't know is whether this is a bug or not. Maybe someone with more knowledge about emberjs can help shed some light on that.
See the question for more details, but the generic answer that I worked for me when saving a model with a belongsTo relationship (and you specifically need that relationship to be serialized) is to call .get() on the properties and then save() them in then().
It boils down to this:
var file = this.store.createRecord('file', {
fileName: 'the_name.txt',
filePath: '/the/path',
type: null,
version: null
});
// belongsTo set() here
file.set('type', selectedType)
.set('version', selectedVersion);
Ember.RSVP.all([
file.get('type'),
file.get('version')
]).then(function(values) {
var onSuccess = function() {
this.transitionToRoute('files');
}.bind(this);
var onFail = function() {
alert("failure");
this.set('uploadError', true);
}.bind(this);
// Save inside then() after I call get() on promises
file.save().then(onSuccess, onFail);
}.bind(this));

How to post json to api method in backbone.js?

i have rest api based on django rest framework, that include next method of creation object, that takes the data in JSON-format on 'myapp/create_obj/' and if the data is correct object will created, otherwise it returns an error also in JSON-format.
def create_obj(request):
stream = StringIO(request.raw_post_data)
data = JSONParser().parse(stream)
serializer = ObjSerializer(data=data, many=True)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data, status=201)
else:
return JSONResponse(serializer.errors, status=400)
Also i tried to create a module on backbone.js, that post the input in form data to this method. Im very new to js, in particular to backbone and i bad understand how backbone works with server api. i have something like
App.module('Createobj', function(Mod, App, Backbone, Marionette, $, _) {
Mod.id = 'create-obj';
Mod.controllers = {};
Mod.Obj = Backbone.Model.extend({
defaults: {
real_ref : '',
share : ''
}
});
Mod.View = Marionette.ItemView.extend({
id: 'create-obj-page',
template: '#tpl-create-obj-page',
model: Mod.obj,
ui: {
'real_ref': 'input[name=real_ref]',
'share': 'input[name=share]',
'error': 'div.error'
},
hammerEvents: {
'tap button': 'submit:tap'
},
hammerOptions: {
tap: true
},
showError: function(message) {
this.ui.error
.text(message)
.show();
},
hideError: function() {
this.ui.error.hide();
},
});
Mod.Controller = SRClient.PageController.extend({
id: Mod.id + '.main',
ViewClass: Mod.View,
setup: function() {
this.listenTo(this.view, 'submit:tap', this.submit);
},
submit: function() {
var real_ref = this.view.ui.real_ref.val(),
share = this.view.ui.share.val();
if (!real_ref || !share) {
this.view.showError($t('create-obj.error_empty_fields'));
return;
}
App.vent.trigger('loading-screen:show', $t('app.please_wait'));
var obj = new Mod.obj({
real_ref : this.view.ui.real_ref.val(),
share : this.view.ui.share.val()
});
}});
Mod.addInitializer(function() {
Mod.Controllers = {
default: Mod.Controller
};
App.pageControllers[Mod.id] = Mod;
});
});
What i need to do, that data which i input in webform sends to 'myapp/create_obj' in json-format? Thanks!
Backbone expects a RESTful api so instead of being the endpoint an action like create_obj, REST works with Resources and with HTTP methods. In your case you could have a Model like this:
var Obj = Backbone.Model.extend({
defaults: {
real_ref : '',
share : ''
}
});
and a collection like this
var Objects = Backbone.Collection.extend({
url: 'myapp/obj',
model: Obj
});
the collection has a propetry url that specifies the server endpoint. So the operations will be
POST /myapp/obj/ for create a new item
GET /myapp/obj/:id/ if you want to retreive an specific item
GET /myapp/obj/ retreving the whole list
PUT /myapp/obj/:id/ update an item
DELETE /myapp/obj/:id/ delete an item
Tastypie is a good framework to create RESTful api with Django.

Categories