RejectChanges() doesn't undo changes when changes are made on a new entity? - angularjs

I have a factory with that returns a new entity:
//myDataFactory
//some other code here...
function create() {
return manager.createEntity(entityName);
}
In my controller, when ever the backend returns a 404 (not found), I simply trigger that create() method when the controller is activated, otherwise I set the object to whatever was returned.
//myDataController
//some other code here...
init();
function init() {
var promises = [
getMyData()
];
console.log('populating MyData');
return q.all(promises).then(function(){
logger.info('populated MyData.');
});
}
function getMyData() {
return myDataFactory.getMyData(true).then(
setMyData,
createNewMyData
);
}
function setMyData(data) {
vm.myData = data[0];
}
function createNewMyData() {
vm.myData = myDataFactory.create();
}
In the UI, I have an undo button, that simply calls this function in the myDataController:
function undo() {
vm.myData.entityAspect.rejectChanges();
vm.termsForm.$setPristine(true);
}
The undo() function above works really well when there is an object returned from the database. But when I try making changes to a newly created entity which isn't saved yet, when I click undo, it's not going back to it's original value. Why? How do I resolve this? Any help would be greatly appreciated. :D
I am using angularjs with breeze btw.

"Original values" are the values that an existing entity had prior to your current, unsaved changes.
A new entity ... one not retrieved from the server and not yet saved ... lacks "original values". It only has "current values". Therefore, rejectChanges has nothing to roll back to.
There are other important differences as well. Look at the thing.entityAspect.entityState.name of a thing entity both before and after calling rejectChanges.
If the state before is "Modified", the state afterward is "Unchanged". But if the state before is "Added", the state afterward is "Detached" ... meaning that the thing is no longer in the EntityManager cache and is ripe for garbage collection.
With these facts in mind, what would you like the behavior to be? Once you know, we can work out a satisfying plan for your scenario.

For those stuck, here is my solution based on what I gathered from Mr. Ward's answer. I used entityState.isAdded() instead.
function undo() {
if (myDataIsNew()) {
resetMyData();
} else {
vm.myData.entityAspect.rejectChanges();
}
setPristineForm();
}
function myDataIsNew() {
// A new entity in cache that does not exist in the backend database
return vm.myData.entityAspect.entityState.isAdded();
}
function resetMyData() {
//clear each property.
}

Related

How $watch changes of a variable in a service from component's controller?

I have been through all related topics on SO, namely these two:
$watch not detecting changes in service variable
$watch not detecting changes in service variable
are tackling the same issue, but i failed to make it working. Unlike in the above cases, I am using a controller from a component, hence maybe this is related to lacking binding in components, idk. Hope for some experinced assistance.
Have a service:
(function (angular) {
'use strict';
angular
.module('Test')
.service('ShareData', ShareData);
ShareData.$inject = [];
function ShareData() {
let vm = this;
vm.indexes = [];
vm.setIndexes = function(firstIndexParam, lastIndexParam, message) {
if (leaderIndexParam !== undefined || partnerIndexParam !== undefined) {
vm.indexes.mainIndex = firstIndexParam;
vm.indexes.secondaryIndex = lastIndexParam;
vm.indexes.message = message;
}
};
vm.getIndexes = function() {
return vm.indexes;
};
}
})(angular);
It is used in 3 components. Two of them are sending data into the service, the third one uses this data. Sending of data is accomplished in the following way, works:
ShareData.setIndexes(firstIndex, secondIndex, 'update_indexes');
Now here is my problem. In main parent controller i can comfortably access the data by
ShareData.getIndexes();
But my issue is that I need changes in indexes to trigger certain actions in parent controller, so I tried so do as stipulated by relevant questions here on SO:
$scope.$watch('ShareData.getIndexes()', function(newVal) {
console.log('New indexes arrived', newVal);
});
In main controller, I am injecting the service:
TabController.$inject = ['ShareData'];
and using it like:
let indexService = ShareData.getIndexes();
As i said, I can get the data when I am explicitly calling the function. The issue is that it needs to be triggered by the service itself.
It does not work regardless of shamanistic ceremonies a made :) Now, obviously, I am missing something. Should I somehow bind this service to the component, and if yes how is it done? Or maybe the solution is totally dysfunctional and impossible to achieve in my circumstances? An advise is appreciated!
UPDATE: I already have a functional solution with the same service working with $rootScope.$broadcast, however my aim is to get rid of it and not work with the $rootScope.
The problem is that you never actually change the value of vm.indexes - it always points to the same array. setIndexes only modifies properties of this array. That's why $watch, which by default checks for reference equality only, fails to spot the changes.
There are (at least) two ways of solving this: either make $watch check the object equality instead, by adding a third param there:
$scope.$watch('ShareData.getIndexes()', function(newVal) {
console.log('New indexes arrived', newVal);
}, true);
... or (better, in my opinion) rewrite the set function so that it'll create a new instance of indexes instead when there's a change:
vm.setIndexes = function(firstIndexParam, lastIndexParam, message) {
if (leaderIndexParam === undefined && partnerIndexParam === undefined) {
return;
}
vm.indexes = vm.indexes.slice();
Object.assign(vm.indexes, {
mainIndex: firstIndexParam,
secondaryIndex: lastIndexParam,
message: message
});
};
As a sidenote, simply calling setIndexes() does not trigger the digest - and $watch listener only checks its expression when digest is triggered.

Publish/Subscribe not working automatically when data added to the mongodb

I have the following publisher and subscriber code.
It works for the first time when the app starts, but when I try to insert data directly into the Mongo database, it will not automatically update the user screen or I don't see the alert popping.
Am I missing something?
Publish
Meteor.publish('userConnections', function(){
if(!this.userId){
return;
}
return Connections.find({userId: this.userId});
})
Subscribe
$scope.$meteorSubscribe('userConnections').then(function () {
var userContacts = $scope.$meteorCollection(Connections);
alert("subscriber userConnections is called");
if (userContacts && userContacts[0]) {
....
}
}, false);
First off, if you are not using angular-meteor 1.3 you should be. The API has changed a lot. $meteorSubscribe has been deprecated!
To directly answer your question, $meteorSubscribe is a promise that gets resolved (only once) when the subscription is ready. So, it will only ever be called once. If you look at the documentation for subscribe you'll see how to make the binding "reactive", by assigning it to a scope variable. In your case it would be something like:
$scope.userContacts = $scope.$meteorCollection(Connections);
Doing it this way, when the collection gets updated, the $scope.userContacts should get updated as well.

angular-meteor: notify client when new document inserted

I am implementing a notification system using angularjs and meteor.
In my publication code,
I have something like this:
var retVal = Notifications.find({recipient: userId});
var handle = retVal.observeChanges({
//when a new notification is added
added: function (doc, idx) {
count++;
if (!initializing){
console.log("A record was added");
self.changed("counts", userId, {count: count});
}
},
removed: function (doc, idx) {
count--;
self.changed("counts", userId, {count: count});
}
});
and in the end I return retVal.
In my controller, I subscribe to that publication.
The code seems fine and the server triggers the added function whenever a new document is added. But how do I notify the client (something like trigger a function in my controller) when a new document is added? The added function only triggers in the server.
I can't see your publication header, do you expect parameters there?
For binding a collection all you need to do is use the $meteorCollection service like that:
$scope.notifications = $meteorCollection(Notifications);
We just updated our API (version 0.6.0-alpha) and it does observeChanges internally to look for any change in the collection.
But don't forget to subscribe to that collection - you can do that in 2 ways:
$meteorSubscribe.subscribe("publicationName", parameters) - which returns a promise.
$scope.notifications = $meteorCollection(Notification).subscribe("publicationName", parameters); - which is shorter but doesn't return a promise.
If one of the parameters changes the publication, you should surround it with autorun like that:
$meteorUtils.autorun($scope, function(){
$meteorSubscribe.subscribe("publicationName", {
limit: parseInt($scope.getReactively('perPage')),
skip: (parseInt($scope.getReactively('page')) - 1) * parseInt($scope.getReactively('perPage')),
sort: $scope.getReactively('sort')
}));
});
$scope.getReactively is a new method we added that makes a regular $scope variable to a reactive one. this means that when it changes, that autorun will re-run.
Hope it helps, let me know how can I improve the answer and the documentation.
I think that you should replicate your observeChanges() on the client.
So, it will be able to observe the client side collection that is created and synchronized by the subscribe() function.

Backbone Event functions unable to access changed object that caused the event

Here is a little backboneJS program - written in Typescript - where I am trying to trigger various functions based on changes in the data in the model. While the function gets triggered, I'm having a hard time getting the triggered function to be able to access the model instance which has been changed (added, deleted, modified etc.) causing the event. In this little program, I've made a little API call e.change.get("answer") which I'm pretty sure is wrong, but I'm unable to find the right API call.
class Answers extends Backbone.Collection {
constructor(options) {
super(options);
var self = this;
this.on("add", function (e) {
console.log("Added a new answer : " + e.change.get("answer")); // Need to access the newly added answer instance here
}, this);
}
model = Answer;
}
You should be able to access it with
this.on("add", function (model) {
console.log("Added a new answer : " + model);
});
The first argument is the model (see http://backbonejs.org/#Events-catalog)

How to not make backbone.js use the save response as model attributes

So when I save a model on the backend, My api send back a response telling everything went fine and giving you some other pointers in json format
My problem is that backbone think I want to use that response as attributes of my model and automatically dump them in the model attributes..
I just saved it on the front-end and do not want to save the attributs again.
That is the what Backbone.Model.parse is for. By default, it is just a pass-through, so you don't need to call "super".
Let's say you only care about two properties that come back (id and foo) and you don't care about anything else:
var myModel = Backbone.Model.extend({
parse : function(resp, xhr) {
return {
id: resp.id,
foo: resp.foo
};
}
});
Note that I included "id" in my example. It is really important that creates (POST) return an id property. Without it, the Backbone model won't know how to update/delete in the future. Even if it has a different name for id (like "objectId"), you should still set the id in this function.
Indeed that's the default behaviour, and if you want to change it, you have to overwrite some Backbone functions.
Looking at how save is implemented, you have two options - either overwrite save for your model, or overwrite parse to make it aware of the data you are sending.
http://documentcloud.github.com/backbone/docs/backbone.html#section-41
Or, you could give up sending the 'pointers' in the response, because an empty response means that the model does not change after save.
I have the exact issue you are encountering. Backbone is a pretty young framework with the additional fact that javascript is really dynamic. So the saying that there are a thousand ways to solve a problem applies really well here.
I think a more suitable way to go about this is to employ something called Mixins. Here's what I did:
define([
'underscore',
'backbone',
'jquery'
], function (_, Backbone, $) {
return {
parse: function(response, xhr){
var data = response;
if(response.response && response.response.status != 0){
return {};
}
if(response.response && response.response.data)
{
data = _.first(response.response.data);
if(typeof data == 'undefined'){
data={};
}
}
if(_.isFunction(this.postParse)){
return this.postParse.call(this, data);
}
return data;
}
}
});
As you can see, I've overridden the Backbone.Model.parse prototype method and came up with my own that takes in a response. And parse the response according to my server's spec. In you case, you would implement whatever it takes to understand your server's response.
With the ground work out of the way, specifying a model is very easy:
var group = Backbone.Model.extend(
_.extend({}, ModelMixin, {
initialize:function () {
}
})
);
return group;
Voila! All the parse methods and checks that you need to write is encapsulated in that one ModelMixin "superclass".

Resources