Updating Backbone Model Attributes Dynamically - model-view-controller

I have a model that is part of a collection and retrieves data from the api. This model contains (among other attributes) the following attributes:
updatedDate //-> value retreived from API/DB
lastUpdateAttempt //-> value retrieved from API/DB
status //-> value NOT retrieved from API/DB, depends on values of above two attributes ("updated", "error", "out of date", etc...).
My question is, how can/when should I set the status attribute? Is there a way where I can dynamically set status when trying to retrieve the value? (i.e. modelObj.get("status") -> calls function to calculate value, returns result). Or should I call a function from the view to update this attribute on initialize, then add an event listener that does the same on change? (<-- somehow doesn't seem like the best solution)
I have a feeling I'm overthinking this and there is a really practical way of doing this, but I'm still a bit inexperienced with Backbone.
Thanks.

You can set the initial value of status, and listen for further changes to updatedDate or lastUpdateAttempt when the model is initialized.
Something like
Backbone.Model.extend({
initialize: function(){
this.updateStatus();
this.on("change:updatedDate change:lastUpdateAttempt",this.updateStatus);
},
updateStatus: function(){
// your logic
}
});
Or you can try this weird way (not at all tested, just a thought), which is somewhat like updating the status while accessing it. Might help if you want to control the frequency of status updates. (if you are likely to access the status way less than the number of changes that is likely to occur with the other two properties)
Backbone.Model.extend({
initialize: function(){
this.updateStatus();
this.on("updateStatus",this.updateStatus);
},
updateStatus: function(){
// your logic
}
});
and access the status like, model.trigger('updateStatus').get('status')

Related

MVC Controller w/ two arguments of same ViewModel type does not bind correctly

I have the following controller action:
public JsonResult AcceptChanges(RoomPricing currentData, RoomPricing lastSaveData)
{
...
}
This controller receives JSON encoded objects from my AJAX request:
$.ajax(
{
type: "POST",
url: _controllerURL,
data: JSON.stringify({ currentData: _currentData, lastSaveData: _lastSaveData }),
...
});
The AJAX request data is derived from a form in my partial view, which uses a ViewModel of type RoomPricing. Current and lastSave data are respectively the updated and stale serialized versions of the form. The purpose of these objects is to do form update checks server-side. Server-side because the RoomPricing model includes an enumerable and other junk that would make reliable update checking complex and obnoxious to perform client-side.
Now, when the controller receives the currentData and lastSaveData, it automagically creates the RoomPricing objects, BUT both objects are identical, taking on the values of currentData. To be clear: lastSaveData is created, but only in name, as its contents are identical to that of currentData (and so ignoring the data that was passed by AJAX, which I assume goes into the void).
I expect that this behavior is a side effect of MVC trying to be helpful with Model Binding. Does anyone have a suggestion for getting around this problem? Making a super-ViewModel with two RoomPricing objects to use as the controller argument did not resolve this issue.
Thanks in advance!
Edit: The current and lastSave data comes from the following JQuery code:
var $lastSaveFormData = null;
function AjaxSubmitForm() {
var $lastSaveSerialized = ($lastSaveFormData == null ? null : $lastSaveFormData)
var $form = $('#MyForm');
submitOverrideForm(
$form.serialize(), // currentData
$lastSaveSerialized, // lastSaveData
$form.attr('action'),
);
$lastSaveFormData = $form.serialize();
}
Through the above I'm able to keep a record of all changes since the last save. Although the models are somewhat complex, the size of the data being sent is quite small so I figured I'd compare the data server-side, and here we are. Last thing of note is that I've verified that at this point - JSON.stringify({ currentData: _currentData, lastSaveData: _lastSaveData } - the encoded data is as expected...currentData and lastSaveData are unique if form updates have taken place.
Edit: I just noticed something else. Here is the data being sent to the server as well as the data received server-side just prior to being bound to the model:
_currentData, # AJAX call:
"Book%5B0%5D.Author=1&Book%5B0%5D.Title=100&Book%5B0%5D.IsPaperback=false&Book%5B1%5D.Author=2&Book%5B1%5D.Title=2222&Book%5B1%5D.IsPaperback=false"
_lastSaveData # AJAX call:
"Book%5B0%5D.Author=1&Book%5B0%5D.Title=100&Book%5B0%5D.IsPaperback=false&Book%5B1%5D.Author=2&Book%5B1%5D.Title=77&Book%5B1%5D.IsPaperback=false"
JSON received server-side, just before model binding:
{"currentData": "Book[0].Author: 1,1 Book[0].Title: 100,100
Book[0].IsPaperback: false,false Book[1].Author: 2,2 Book[1].Title:
2222,77 Book[1].IsPaperback: false,false", "lastSaveData":"false"}
Its like MVC is trying to bind the distinct values to a single model, realizes it cant, and drops the 'lastSave' data. Then, when the model hits the controller, it discovers that two models are anticipated, so it uses this model for both. Why is it behaving like this and how can I fix it?
You can add another ViewModel:
public class CurrentAndLastSavedRoomPricingViewModel
{
RoomPricing CurrentData {get;set;}
RoomPricing LastSaveData {get;set;}
}
and get it in controller:
public JsonResult AcceptChanges(CurrentAndLastSavedRoomPricingViewModel data)
{
...
}
passing this model with ajax:
$.ajax(
{
type: "POST",
url: _controllerURL,
data: {data: { currentData: _currentData, lastSaveData: _lastSaveData }},
...
});
Or you can get last saved data on server from database and don't pass it from client.

In Meteor, where do I model my business rules?

Beginner question : I've worked through the Try Meteor tutorial. I've got fields in my HTML doc, backed by helper functions that reference collections, and BOOM --> the fields are updated when the data changes in the DB.
With the "Hide completed" checkbox, I've also seen data-binding to a session variable. The state of the checkbox is stored in the Session object by an event handler and BOOM --> the list view is updated "automatically" by its helper when this value changes. It seems a little odd to be assigning to a session object in a single page application.
Through all this, my js assigns nothing in global scope, I've created no objects, and I've mostly seen just pipeline code, getting values from one spot to another. The little conditional logic is sprayed about wherever it is needed.
THE QUESTION... Now I want to construct a model of my business data in javascript, modelling my business rules, and then bind html fields to this model. For example, I want to model a user, giving it an isVeryBusy property, and a rule that sets isVeryBusy=true if noTasks > 5. I want the property and the rule to be isolated in a "pure" business object, away from helpers, events, and the meteor user object. I want these business objects available everywhere, so I could make a restriction, say, to not assign tasks to users who are very busy, enforced on the server. I might also want a display rule to only display the first 100 chars of other peoples tasks if a user isVeryBusy. Where is the right place to create this user object, and how do I bind to it from my HTML?
You can (and probably should) use any package which allows you to attach a Schema to your models.
Have a look at:
https://github.com/aldeed/meteor-collection2
https://github.com/aldeed/meteor-simple-schema
By using a schema you can define fields, which are calculated based on other fields, see the autoValue property: https://github.com/aldeed/meteor-collection2#autovalue
Then you can do something like this:
// Schema definition of User
{
...,
isVeryBusy: {
type: Boolean,
autoValue: function() {
return this.tasks.length > 5;
}
},
...
}
For all your basic questions, I can strongly recommend to read the DiscoverMeteor Book (https://www.discovermeteor.com/). You can read it in like 1-2 days and it will explain all those basic questions in a really comprehensible way.
Best Regards,
There is a very good package to implement the solution you are looking for. It is created by David Burles and it's called "meteor-collection-helper". Here it the atmosphere link:
You should check the link to see the examples presented there but according to the description you could implement some of the functionality you mentioned like this:
// Define the collections
Clients = new Mongo.Collection('clients');
Tasks = new Mongo.Collection('tasks');
// Define the Clients collection helpers
Clients.helpers({
isVeryBusy: function(){
return this.tasks.length > 5;
}
});
// Now we can call it either on the client or on the server
if (Meteor.isClient){
var client = Clients.findOne({_id: 123});
if ( client.isVeryBusy() ) runSomeCode();
}
// Of course you can use them inside a Meteor Method.
Meteor.methods({
addTaskToClient: function(id, task){
var client = Clients.findOne({_id: id});
if (!client.isVeryBusy()){
task._client = id;
Tasks.insert(task, function(err, _id){
Clients.update({_id: client._id}, { $addToSet: { tasks: _id } });
});
}
}
});
// You can also refer to other collections inside the helpers
Tasks.helpers({
client: function(){
return Clients.findOne({_id: this._client});
}
});
You can see that inside the helper the context is the document transformed with all the methods you provided. Since Collections are ussually available to both the client and the server, you can access this functionality everywhere.
I hope this helps.

Kendo - creating a custom model property with value from server property

I have a property called Copies which is defined on the server that represents the default number of copies allowed. And I can update this value and it will update an input field on my UI.
however, I would like to be able to reset the Copies property to the original value if the user resets this field on the UI.
My idea was to define a custom property on my kendo datasource model called originalValue that references the Copies property. but this just seems to override the Copies property if I do something like this.
schema: {
data: 'd',
total: function (data) {
return data.d.length;
},
model: {
originalCopies: "Copies"
}
}
how can I go about creating a custom property like this which is basically a immutable clone of my Copies property?
You can try to do it on the server side, just create a separate property "OriginalCopies" and set it to Copies. Once passed to the client side , it will lose its immutability.
Something similar could be done on the client side as well. JSON.stringify your Copies and set
OriginalCopies to the JSON.parse value of the stringified variable as:
var copies = JSON.stringify(data.Copies);
data.OriginalCopies = JSON.parse(copies);

How to manage new Breeze entities which are aggregate roots?

I have a domain model which has a Customer, which in turn has 1 Address (1:1) and 1 or more Phone numers (1:M).
Customer has user supplied PK (a string), while Address and Phone use identity column (server generated).
I am struggling in trying to understand how to manage Breeze entity creation for a "Add new Customer" screen.
The form on the screen allows user to enter Customer, Address, and Phone data.
I am using Durandal and Knockout so my "customeradd.js" viewmodel looks something like this:
// -- snip ---
var customer = ko.observable(),
hasChanges = ko.computed(function () {
return datacontext.hasChanges();
});
var vm = {
hasChanges: hasChanges,
customer: customer,
activate: activate
};
return vm;
function activate() {
customer(datacontext.createCustomer());
}
// -- snip ---
and my "/services/datacontext.js" :
// -- snip ---
breeze.NamingConvention.camelCase.setAsDefault();
var manager = new breeze.EntityManager(config.remoteServiceName);
var hasChanges = ko.observable(false);
manager.hasChangesChanged.subscribe(function (eventArgs) {
hasChanges(eventArgs.hasChanges);
});
function createVehicle() {
return manager.createEntity("Customer");
}
// -- snip ---
My questions are following:
Once I create a Customer, do I need to create Address and list of Phones and add them to Customer entity before making it a KO observable? Or is this done automatically by createEntity() method?
How do I create a Customer but without having to specify the Id? If I set the key to null or '', Breeze complains ("Error: Cannot attach an object to an EntityManager without first setting its key or setting its entityType 'AutoGeneratedKeyType' property to something other than 'None'"). However, if I generate the temp key (using either breeze.core.getUuid() or something else), then it shows up in my Id form field, and I really want the end user to specify it....Do I have to resort to extending the entity with extra field and then do the swapping and validation before saving (I don't like this idea at all)? Is there a better way?
In order to enable/disable buttons on my form I am tracking if there are changes in EntityManager. But every time entity is created, it is automatically in 'added' state so hasChanges is true. What I want is for changes to be picked up only if user edits the form (and therefore makes changes to underlaying entity). What is the best way to approach this?
BTW, I have seen this recommendation to register custom constructor for entity (I have already implemented it but I am still not clear how to let user supply their own id and to flag entity as modified only when user edits it...)
I realize this has been up for a while, but here are my thoughts (in case anyone comes looking).
If you use the entityManager to create your customerl and everything is specified correctly in the metadata, you can just create the customer and add phone numbers/addresses as needed. Breeze automatically makes an entity's properties observable (if specified correctly and if breeze knows that KO is being used)
If you can only do it the way that you say, then you are stuck. Ideally, you would have a user-entered ID which is NOT the key (though you could still force it to be unique) and a database-generated key, which Breeze will manage behind the scenes (assigning a negative key until it is saved to the data store, then updating the key and all related keys without any input from you).
if you use the 2nd approach for answer 2, then your buttons can easily be enabled and disabled using ko data-binding. When you create the entity, save its value to the viewmodel (custSource). Then you can add to the save button the data-bind="disable: custSource == Customer(), enable: custSource != Customer()". (You might need to play around with the syntax -- I haven't tested that part yet)
I don't think you need a custom constructor unless you are doing something different from what I understand.
PS. you should be aware that I believe Breeze wants Knockout defined as 'ko', while Durandal definitely expects it to be 'knockout', so you will probably need a 'map' property in your require.config
I think you could solve some of your problems by taking a slightly different approach to your entity creation. Here's your current approach:
Create a customer entity
User modifies that entity
Save the changes
Instead, try this:
User enters customer information
Create and save the customer entity
I realize that this doesn't really answer your questions, but I've found the second approach to be much easier to implement. Just have the user enter all the information you need to create a customer, and then supply those values to createEntity.
customeradd.js
// -- snip ---
var vm = {
customerId: ko.observable(),
address: ko.observable(""),
phoneNumbers: ko.observableArray([]),
submit: submit
};
return vm;
function submit() {
datacontext.createCustomer(
vm.customerId(),
vm.address(),
vm.phoneNumbers());
}
// -- snip ---
/services/datacontext.js
// -- snip ---
/**
* Creates a new customer.
* #param {int} id - The customer's id number.
* #param {string} address - The customer's address.
* #param {string[]} phoneNumbers - An array of the customer's phone numbers.
*/
function createCustomer(id, address, phoneNumbers) {
return manager.createEntity("Customer",
{
id: id,
address: address,
phoneNumber: phoneNumbers
});
}
// -- snip ---

Knockout Mapping - Fill Observable Arrays keeping Items' methods

I've been facing a problem that is basically the following:
I have a knockout ViewModel which contains observable arrays of items with observable properties and methods.
I need to pull data from the server. The methods need to exist after data is taken from server. So I create a new ViewModel and then update its value from what comes from server. (THIS DOES NOT WORK, THE RESULTING ARRAY HAS NO ITEMS)
If I create, with mapping, a new object using var newObj = ko.mapping.fromJS(data) the resulting Array has items, but its items have no methods. It spoils my Bindings.
The fiddle of my problem: http://jsfiddle.net/claykaboom/R823a/3/ ( It works util you click in "Load Data From The Server" )
The final question is: What is the best way to have items on the final array without making the loading process too cumbersome, such as iterating through every item and filling item's properties in order to keep the previously declared methods?
Thanks,
I changed your code little bit. Check this version of JSFiddle.
var jsonFromServer = '{"ModuleId":1,"Metadatas":[{"Id":1,"MinValue":null,"MaxValue":null,"FieldName":"Teste","SelectedType":"String","SelectedOptionType":null,"IsRequired":true,"Options":[]}]}';
Your code doesnt work because your jsonFromServer variable does not contain methods we need at binding like you described in your question. ( -- > Metadatas )
So we need to define a custom create function for Metadata objects at the mapping process like this :
var mapping = {
'Metadatas': {
create: function(options) {
var newMetaData = new MetadataViewModel(options.parent);
newMetaData.Id(options.data.id);
newMetaData.FieldName(options.data.FieldName);
newMetaData.SelectedType(options.data.SelectedType);
newMetaData.SelectedOptionType(options.data.SelectedOptionType);
newMetaData.IsRequired(options.data.IsRequired);
newMetaData.Options(options.data.Options);
// You can get current viewModel instance via options.parent
// console.log(options.parent);
return newMetaData;
}
}
}
Then i changed your load function to this :
self.LoadDataFromServer = function() {
var jsonFromServer = '{"ModuleId":1,"Metadatas":[{"Id":1,"MinValue":null,"MaxValue":null,"FieldName":"Teste","SelectedType":"String","SelectedOptionType":null,"IsRequired":true,"Options":[]}]}';
ko.mapping.fromJSON(jsonFromServer, mapping, self);
}
You dont have to declare a new viewModel and call ko.applyBindings again. Assigning the updated mapping to current viewModel is enough. For more information check this link. Look out for customizing object construction part.
The final question is: What is the best way to have items on the final
array without making the loading process too cumbersome, such as
iterating through every item and filling item's properties in order to
keep the previously declared methods?
As far as i know there is no easy way to do this with your object implemantation. Your objects are not simple. They contains both data and functions together. So you need to define custom create function for them. But if you can able to separate this like below then you dont have to customize object construction.
For example seperate the MetadataViewModel to two different object :
--> Metadata : which contains only simple data
--> MetadataViewModel : which contains Metadata observableArray and its Metadata manipulator functions
With this structure you can call ko.mapping.fromJSON(newMetaDataArray , {} , MetadataViewModelInstance.MetadataArray) without defining a custom create function at the mapping process.

Resources