Angular service not updating on model change - service

In may app I have a service which holds my tasks:
app.factory('Tasks', function () {
var tasks = [];
return {
getAll: function () { return tasks; },
addOne: function (task) { tasks.push(task); },
openBy: function(owner) {
return _.where(tasks, {owner: owner, status: 'open'});
},
doneBy: function(owner) {
return _.where(tasks, {owner: owner, status: 'closed'});
},
};
});
I then show, per owner, either their open tasks or closed tasks.
The problem is that when I update the tasks by using Tasks.addOne(task); the views that use Tasks.openBy(owner) don't get updated. The ones that use Tasks.getAll() do.
Is this because I am returning a new array? If so is there a way of telling the controller to update what it has? Or am I just doing this entirely wrong in the first place and is there a better way to do it?
Any help would be greatly appreciated.
Matthew

What you could do is to call the openBy function in the controller (or directive) rather than in the view and wrap it into a $scope.$watch invocation. As an example:
// Controller body
app.controller('TasksCtrl', function($scope, Tasks) {
$scope.allTasks = Tasks.getAll();
$scope.$watch('allTasks', function() {
// Assume owner is the user and it's initialised somewhere above
$scope.ownedTasks = tasks.openBy(owner);
}, true);
});
This should work, even though I think that it should be possible to do something more elegant maybe!

Related

How can I render data after 10 seconds of actual database update reactively in a particular template in Meteor.js?

I'm currently working on a simple game called Bingo. Now I've made a spectate option in which I need to broadcast the game not real time but with a 10 second delay. Now how can I do that easily ?
The idea to use observe routine seems good but there are at least a couple of ways this can be implemented. One way is to delay the subscription itself. Here's a working example:
import { Meteor } from 'meteor/meteor';
import { TheCollection } from '/imports/collections.js';
Meteor.publish('delayed', function (delay) {
let isStopped = false;
const handle = TheCollection.find({}).observeChanges({
added: (id, fields) => {
Meteor.setTimeout(() => {
if (!isStopped) {
this.added(TheCollection._name, id, fields);
}
}, delay);
},
changed: (id, fields) => {
Meteor.setTimeout(() => {
if (!isStopped) {
this.changed(TheCollection._name, id, fields);
}
}, delay);
},
removed: (id) => {
Meteor.setTimeout(() => {
if (!isStopped) {
this.removed(TheCollection._name, id);
}
}, delay);
}
});
this.onStop(() => {
isStopped = true;
handle.stop();
});
this.ready();
});
Another way would be to create a local ProxyCollection that is only used for rendering purpose. The data would be copied from TheCollection to ProxyCollection with some delay using the same "observe technique" as in the subscription case.
In both scenarios you will need to handle some edge cases, for example:
Should the data be delayed on the initial load?
Should the update be delayed if document is removed?
Should the update be delayed for the user that initialized the change?
They can all be solved by utilizing and adjusting the technique presented above. I believe though, they're outside the scope of this question.
EDIT
To prevent delays on the initial data load you can update the above code as follows:
let initializing = true;
const handle = TheCollection.find({}).observeChanges({
added: (id, fields) => {
if (initializing) {
this.added(TheCollection._name, id, fields);
} else {
Meteor.setTimeout(() => {
if (!isStopped) {
this.added(TheCollection._name, id, fields);
}
}, delay);
}
},
// ...
});
// ...
this.ready();
initializing = false;
At first, it may not be obvious why this works, but everything here is being executed within a fiber. The observeChanges routine "blocks" and it first calls added for each document of the entire initial dataset. Only then it proceeds to the next part of your publish method body.
Something that one should be aware of is because of the behavior described above, a subscription may be stopped before the initial data set is processed and so, before the onStop callback is even defined. In this particular case it shouldn't hurt but sometimes it can be problematic.
You can use .observe(). It will tell you when added/changed events fire and you can do whatever you want in those events. Documentation here.
CollectionName.find().observe({
added: function (document) {
//do something here, like delaying the update
},
changed: function (document) {
//do something here, like delaying the update
},
});

What's the correct Protractor's syntax for Page Objects?

I've come across different types of syntax for Protractor's Page Objects and I was wondering, what's their background and which way is suggested.
This is the official PageObject syntax from Protractor's tutorial. I like it the most, because it's clear and readable:
use strict;
var AngularHomepage = function() {
var nameInput = element(by.model('yourName'));
var greeting = element(by.binding('yourName'));
this.get = function() {
browser.get('http://www.angularjs.org');
};
this.setName = function(name) {
nameInput.sendKeys(name);
};
this.getGreeting = function() {
return greeting.getText();
};
};
module.exports = AngularHomepage;
However, I've also found this kind:
'use strict';
var AngularPage = function () {
browser.get('http://www.angularjs.org');
};
AngularPage.prototype = Object.create({}, {
todoText: { get: function () { return element(by.model('todoText')); }},
addButton: { get: function () { return element(by.css('[value="add"]')); }},
yourName: { get: function () { return element(by.model('yourName')); }},
greeting: { get: function () { return element(by.binding('yourName')).getText(); }},
todoList: { get: function () { return element.all(by.repeater('todo in todos')); }},
typeName: { value: function (keys) { return this.yourName.sendKeys(keys); }} ,
todoAt: { value: function (idx) { return this.todoList.get(idx).getText(); }},
addTodo: { value: function (todo) {
this.todoText.sendKeys(todo);
this.addButton.click();
}}
});
module.exports = AngularPage;
What are the pros/cons of those two approaches (apart from readability)? Is the second one up-to-date? I've seen that WebdriverIO uses that format.
I've also heard from one guy on Gitter that the first entry is inefficient. Can someone explain to me why?
Page Object Model framework becomes popular mainly because of:
Less code duplicate
Easy to maintain for long
High readability
So, generally we develop test framework(pom) for our convenience based on testing scope and needs by following suitable framework(pom) patterns. There are NO such rules which says that, strictly we should follow any framework.
NOTE: Framework is, to make our task easy, result oriented and effective
In your case, 1st one looks good and easy. And it does not leads to confusion or conflict while in maintenance phase of it.
Example: 1st case-> element locator's declaration happens at top of each page. It would be easy to change in case any element locator changed in future.
Whereas in 2nd case, locators declared in block level(scatter across the page). It would be a time taking process to identify and change the locators if required in future.
So, Choose which one you feel comfortable based on above points.
I prefer to use ES6 class syntax (http://es6-features.org/#ClassDefinition). Here, i prepared some simple example how i work with page objects using ES6 classes and some helpful tricks.
var Page = require('../Page')
var Fragment = require('../Fragment')
class LoginPage extends Page {
constructor() {
super('/login');
this.emailField = $('input.email');
this.passwordField = $('input.password');
this.submitButton = $('button.login');
this.restorePasswordButton = $('button.restore');
}
login(username, password) {
this.email.sendKeys(username);
this.passwordField.sendKeys(password);
this.submit.click();
}
restorePassword(email) {
this.restorePasswordButton.click();
new RestorePasswordModalWindow().submitEmail(email);
}
}
class RestorePasswordModalWindow extends Fragment {
constructor() {
//Passing element that will be used as this.fragment;
super($('div.modal'));
}
submitEmail(email) {
//This how you can use methods from super class, just example - it is not perfect.
this.waitUntilAppear(2000, 'Popup should appear before manipulating');
//I love to use fragments, because they provides small and reusable parts of page.
this.fragment.$('input.email').sendKeys(email);
this.fragment.$('button.submit')click();
this.waitUntilDisappear(2000, 'Popup should disappear before manipulating');
}
}
module.exports = LoginPage;
// Page.js
class Page {
constructor(url){
//this will be part of page to add to base URL.
this.url = url;
}
open() {
//getting baseURL from params object in config.
browser.get(browser.params.baseURL + this.url);
return this; // this will allow chaining methods.
}
}
module.exports = Page;
// Fragment.js
class Fragment {
constructor(fragment) {
this.fragment = fragment;
}
//Example of some general methods for all fragments. Notice that default method parameters will work only in node.js 6.x
waitUntilAppear(timeout=5000, message) {
browser.wait(this.EC.visibilityOf(this.fragment), timeout, message);
}
waitUntilDisappear(timeout=5000, message) {
browser.wait(this.EC.invisibilityOf(this.fragment), timeout, message);
}
}
module.exports = Fragment;
// Then in your test:
let loginPage = new LoginPage().open(); //chaining in action - getting LoginPage instance in return.
loginPage.restorePassword('batman#gmail.com'); // all logic is hidden in Fragment object
loginPage.login('superman#gmail.com')

Meteor onRendered function and access to Collections

When user refresh a certain page, I want to set some initial values from the mongoDB database.
I tried using the onRendered method, which in the documentation states will run when the template that it is run on is inserted into the DOM. However, the database is not available at that instance?
When I try to access the database from the function:
Template.scienceMC.onRendered(function() {
var currentRad = radiationCollection.find().fetch()[0].rad;
}
I get the following error messages:
Exception from Tracker afterFlush function:
TypeError: Cannot read property 'rad' of undefined
However, when I run the line radiationCollection.find().fetch()[0].rad; in the console I can access the value?
How can I make sure that the copy of the mongoDB is available?
The best way for me was to use the waitOn function in the router. Thanks to #David Weldon for the tip.
Router.route('/templateName', {
waitOn: function () {
return Meteor.subscribe('collectionName');
},
action: function () {
// render all templates and regions for this route
this.render();
}
});
You need to setup a proper publication (it seems you did) and subscribe in the route parameters. If you want to make sure that you effectively have your data in the onRendered function, you need to add an extra step.
Here is an example of how to make it in your route definition:
this.templateController = RouteController.extend({
template: "YourTemplate",
action: function() {
if(this.isReady()) { this.render(); } else { this.render("yourTemplate"); this.render("loading");}
/*ACTION_FUNCTION*/
},
isReady: function() {
var subs = [
Meteor.subscribe("yoursubscription1"),
Meteor.subscribe("yoursubscription2")
];
var ready = true;
_.each(subs, function(sub) {
if(!sub.ready())
ready = false;
});
return ready;
},
data: function() {
return {
params: this.params || {}, //if you have params
yourData: radiationCollection.find()
};
}
});
In this example you get,in the onRendered function, your data both using this.data.yourData or radiationCollection.find()
EDIT: as #David Weldon stated in comment, you could also use an easier alternative: waitOn
I can't see your collection, so I can't guarantee that rad is a key in your collection, that said I believe your problem is that you collection isn't available yet. As #David Weldon says, you need to guard or wait on your subscription to be available (remember it has to load).
What I do in ironrouter is this:
data:function(){
var currentRad = radiationCollection.find().fetch()[0].rad;
if (typeof currentRad != 'undefined') {
// if typeof currentRad is not undefined
return currentRad;
}
}

how to resolve optional url path using ng-resource

There are restful APIs, for instance:
/players - to get list for all players
/players{/playerName} - to get info for specific player
and I already have a function using ng-resource like:
function Play() {
return $resource('/players');
}
Can I reuse this function for specific player like:
function Play(name) {
return $resource('/players/:name', {
name: name
});
}
so I want to...
send request for /players if I didn't pass name parameter.
send request for /players/someone if I passed name parameter with someone
Otherwise, I have to write another function for specific play?
Using ngResource it's very, very simple (it's basically a two-liner). You don't need even need to create any custom actions here*.
I've posted a working Plunkr here (just open Chrome Developer tools and go to the Network tab to see the results).
Service body:
return $resource('/users/:id/:name', { id:'#id', name: '#name' })
Controller:
function( $scope, Users ){
Users.query(); // GET /users (expects an array)
Users.get({id:2}); // GET /users/2
Users.get({name:'Joe'}); // GET /users/Joe
}
of course, you could, if you really wanted to :)
This is how I did it. This way you don't have to write a custom resource function for each one of your endpoints, you just add it to your list resources list. I defined a list of the endpoints I wanted to use like this.
var constants = {
"serverAddress": "foobar.com/",
"resources": {
"Foo": {
"endpoint": "foo"
},
"Bar": {
"endpoint": "bar"
}
}
}
Then created resources out of each one of them like this.
var service = angular.module('app.services', ['ngResource']);
var resourceObjects = constants.resources;
for (var resourceName in resourceObjects) {
if (resourceObjects.hasOwnProperty(resourceName)) {
addResourceFactoryToService(service, resourceName, resourceObjects[resourceName].endpoint);
}
}
function addResourceFactoryToService (service, resourceName, resourceEndpoint) {
service.factory(resourceName, function($resource) {
return $resource(
constants.serverAddress + resourceEndpoint + '/:id',
{
id: '#id',
},
{
update: {
method: 'PUT',
params: {id: '#id'}
},
}
);
});
}
The nice thing about this is that it takes 2 seconds to add a new endpoint, and I even threw in a put method for you. Then you can inject any of your resources into your controllers like this.
.controller('homeCtrl', function($scope, Foo, Bar) {
$scope.foo = Foo.query();
$scope.bar = Bar.get({id:4});
}
Use Play.query() to find all players
Use Play.get({name:$scope.name}) to find one player

Ember - clear form after submitting

I created very simple Ember app, using Ember Data. There is one form where the user creates the entity and submits. It's in BandsNewView (created automatically by Ember), controlled by BandsNewController:
App.BandsNewController = Ember.Controller.extend({
cancel: function() {
this.transitionTo('bands');
},
save: function() {
App.Band.createRecord(this);
this.get('store').commit();
this.set('name');
this.set('description');
this.transitionTo('bands');
}
});
I wonder whether there is simplier solution to "clean up" (i.e empty) the form after saving new Band entity? Can I say something like this.set(), which would empty all the fields? Or is my approach essentially wrong and should I do it completely differently?
The pattern that I've been enjoying is creating and destroying the object on enter and exit of the route itself.
App.BandsNewRoute = Ember.Route.extend({
model: function(params) {
return App.Band.createRecord({});
},
save: function() {
this.get('currentModel.store').commit();
return this.transitionTo('bands');
},
exit: function() {
var model = this.get('currentModel');
if (model.get("isNew") && !model.get("isSaving")) {
return model.get('transaction').rollback();
}
}
});
As you can see, it makes the exit function a little more complex, but it will be exactly the same for every object creation route, so you can factor it out. Now your templates can just bind straight to the model's properties and the model will be saved on save, or rolled back on exit (which will clear the form)
If you are planning on possibly changing other data models and not saving them, or have unsaved models, a way to safely clear the model away is to put it in it's own transaction. I only tend to use this though for objects that are not the main focus of my current flow.
App.BandsNewRoute = Ember.Route.extend({
model: function(params) {
var transaction = this.get('store').transaction();
return transaction.createRecord(App.Band, {})
}
});
Everything else can stay the same.