AngularJS two way binding now work with websockets [duplicate] - javascript

Updating the model property has no effect on the view when updating the model in event callback, any ideas to fix this?
This is my service:
angular.service('Channel', function() {
var channel = null;
return {
init: function(channelId, clientId) {
var that = this;
channel = new goog.appengine.Channel(channelId);
var socket = channel.open();
socket.onmessage = function(msg) {
var args = eval(msg.data);
that.publish(args[0], args[1]);
};
}
};
});
publish() function was added dynamically in the controller.
Controller:
App.Controllers.ParticipantsController = function($xhr, $channel) {
var self = this;
self.participants = [];
// here publish function is added to service
mediator.installTo($channel);
// subscribe was also added with publish
$channel.subscribe('+p', function(name) {
self.add(name);
});
self.add = function(name) {
self.participants.push({ name: name });
}
};
App.Controllers.ParticipantsController.$inject = ['$xhr', 'Channel'];
View:
<div ng:controller="App.Controllers.ParticipantsController">
<ul>
<li ng:repeat="participant in participants"><label ng:bind="participant.name"></label></li>
</ul>
<button ng:click="add('test')">add</button>
</div>
So the problem is that clicking the button updates the view properly, but when I get the message from the Channel nothings happens, even the add() function is called

You are missing $scope.$apply().
Whenever you touch anything from outside of the Angular world, you need to call $apply, to notify Angular. That might be from:
xhr callback (handled by $http service)
setTimeout callback (handled by $defer service)
DOM Event callback (handled by directives)
In your case, do something like this:
// inject $rootScope and do $apply on it
angular.service('Channel', function($rootScope) {
// ...
return {
init: function(channelId, clientId) {
// ...
socket.onmessage = function(msg) {
$rootScope.$apply(function() {
that.publish(args[0], args[1]);
});
};
}
};
});

Related

Publish Subscribe service using AngularJS

I am using this code to create a factory for publishing and subscribing messages between controllers , directives and services .
angular.module('app', []);
angular.module('app').controller('TheCtrl', function($scope, NotifyingService) {
$scope.notifications = 0;
$scope.notify = function() {
NotifyingService.publish();
};
// ... stuff ...
NotifyingService.subscribe($scope, function somethingChanged() {
// Handle notification
$scope.notifications++;
});
});
angular.module('app').factory('NotifyingService', function($rootScope) {
return {
subscribe: function(scope, callback) {
var handler = $rootScope.$on('notifying-service-event', callback);
scope.$on('$destroy', handler);
},
publish: function() {
$rootScope.$emit('notifying-service-event');
}
};
});
It is working fine but I want to pass data while I am publishing to someone whos subscribing that ,how do I do that.
Suppose I want to publish a value of 4 , How do I perform that?
If I understood correctly you want to publish value 4 to the 'notifying-service-event' and you want to use that value inside the subscriber.
In order to publish a value you need to pass it to your emit function.
publish: function(msg) {
$rootScope.$emit('notifying-service-event', msg);
}
Then, when you are using this publish function, pass the value you want.
node.on("click", click);
function click() {
NotifyingService.publish(4);
}
While handling the subscribe event:
NotifyingService.subscribe($scope, function somethingChanged(event,msg) {
console.log(msg); //4
scope.number = msg //or whatever you want
scope.$apply();
});
you can find a full example here: https://plnkr.co/edit/CnoTA0kyW7hWWjI6DspS?p=preview
which was an answer to the question:
Display informations about a bubble chart D3.js in AngularJS

AngularJS: How to share scope functions and variables with other controllers

I've multiple controllers in my application, where I have some duplicate code like:
$scope.alert = null;
$scope.addAlert = function (message) {
$scope.alert = { type: 'danger', msg: message };
};
$scope.clearAlerts = function () {
$scope.alert = null;
};
What is the recommended way sharing these scope functions and variables in AngularJS? Using controller inheritance?
Create a one controller and then place common methods inside that controller scope. So that you can use that scope anywhere else and get access to method inside controller.
Controller
app.controller('commonCtrl', function($scope) {
$scope.alert = null;
$scope.addAlert = function(message) {
$scope.alert = {
type: 'danger',
msg: message
};
};
$scope.clearAlerts = function() {
$scope.alert = null;
};
});
Thereafter use scope of this controller by inject it using $controller, and then inside curly brace you could assign common controller scope to the current scope of controller.
Utilization of Common Controller
app.controller('testCtrl', function($scope, $controller) {
//inject comomon controller scope to current scope ,
//below line will add 'commonCtrl' scope to current scope
$controller('commonCtrl', { $scope: $scope });
//common controller scope will be available from here
});
Or more precise way would be using common sharable service, that exposed two method and alert data, you can use this service method by injecting service name inside your controller.
Service
app.service('commonService', function($scope) {
this.alert = null;
this.addAlert = function(message) {
this.alert = {
type: 'danger',
msg: message
};
};
this.clearAlerts = function() {
this.alert = null;
};
});
Utilization of service inside Controller
app.controller('testCtrl', function($scope, commonService) {
console.log(commonService.alert);
commonService.addAlert("Something");
console.log("Updated Alert" + commonService.alert);
});
Hope this has cleared your concept, Thanks.
My own solution for this use case was to define a type of Observer Pattern.
The code was structured in the following way:
var app = angular.module('testModule', []);
app.factory('alertService', ['$timeout', function($timeout){
var alertListeners = [];
this.register = function (listener) {
alertListeners.push(listener);
};
this.notifyAll = function (data) {
for (// each listener in array) {
var listenerObject = alertListeners[i];
try { // do not allow exceptions in individual listeners to corrupt other listener processing
listenerObject.notify(data);
} catch(e) {
console.log(e);
}
}
};
}]).
directive('myAlerts', ['alertService', function(alertService){
var alertDirectiveObserver = function($scope, alertService) {
this.notify = function(data) {
/*
* TO DO - use data to show alert
*/
};
/*
* Register this object as an event Listener. Possibly supply an event key, and listener id to enable more resuse
*/
alertService.register(this);
$scope.on('$destroy', function() {
alertService.unregister(// some listener id);
});
};
return {
restrict: 'A',
template: '<div ng-class="alertClass" ng-show="alertNeeded">{{alertMessage}}</div>',
controller: ['$scope', 'alertService', alertDirectiveObserver],
link: function(scope){
}
}
}]).
controller('alertShowingController', ['$scope', 'alertService', function($scope, alertService){
alertService.notifyAll({'warning', 'Warning alert!!!'})
]);
The alertShowingController is a simple example of how all controllers can simply inject the alertService and generate an event.
My own implementation is more elaborate in that it uses separate event keys to allow the controllers to generate other event notifications.
I could then define a single div that was in a fixed position at the top of the page that would dispay bootstrap alerts.
<div my-alerts ng-repeat="alert in alertList" type="{{alert.type}}" close="closeAlert(alertList, $index)">{{alert.msg}}</div>

How to encapsulate single and temporal events in a service?

I'm trying to encapsulate the events in a service in order to implement a mechanics to subscribe / unsubscribe the listeners when a controller's scope is destroyed. This because I have been using the rootScope.$on in the following way:
if(!$rootScope.$$listeners['event']) {
$rootScope.$on('event', function(ev, data){
// do some...
});
}
or
$scope.$on('$destroy', function(ev, data){
// unsubscribe the listener
});
So I just need one listener of this event, I need to delete the existing listener when the controller is no longer alive, because the function I registered earlier is still being triggered.
So I need to implement a $destroy event listener on my controller, to destroy the listener when the scope is destroyed, but I don't want to do that code each time I create an event.
That's why I want to create a service in where I'm going to encapsulate the events.
angular.module('core').factory('event', [
function() {
var service = {};
service.events = {};
service.on = function(scope, eventId, callback) {
scope.$on('$destroy', function(ev, other){
//unsubscribe
});
service.events[eventId] = callback;
// scope = null; I guess ?
};
service.emit = function(eventId, data){
if (service.events[eventId])
service.events[eventId](data);
else
return new Error('The event is not subscribed');
};
return service;
}
]);
This could be done using $rootScope instead of my own methods but encapsulating the $on and $emit of $rootScope, but at the end I'll have the same issue here.
So these are my questions:
Is a good practice to pass the scope ref value to a service?
What is the meaning of $$destroyed? when this is true means that angularJS has no internal references to the instance?
Should I do a scope = null in my service to let GC delete the object or does angularJS handle an explicit delete?
Is there a better way to do what I want?
What you are trying to accomplish is basically an event bus.
You have also described very well what is wrong with the current implementation.
A different way to approach the problem is to decorate the $rootScope with your bus (or any other event bus for that matter). Here is how:
app.config(function ($provide) {
$provide.decorator('$rootScope', ['$delegate', '$$bus', function ($delegate, $$bus) {
Object.defineProperty($delegate.constructor.prototype, '$bus', {
get: function () {
var self = this;
return {
subscribe: function () {
var sub = $$bus.subscribe.apply($$bus, arguments);
self.$on('$destroy',
function () {
console.log("unsubscribe!");
sub.unsubscribe();
});
},
publish: $$bus.publish
};
},
enumerable: false
});
return $delegate;
}]);
});
Considering the following $$bus implementation (kept basic for simplicity):
app.factory('$$bus', function () {
var api = {};
var events = {};
api.subscribe = function (event) {
if (!events.hasOwnProperty(event.name)) {
events[event.name] = [event];
} else {
events[event.name].push(event);
}
return {
unsubscribe: function () {
api.unsubscribe(event);
}
}
};
api.publish = function (eventName, data) {
if (events.hasOwnProperty(eventName)) {
console.log(eventName);
angular.forEach(events[eventName], function (subscriber) {
subscriber.callback.call(this, data);
});
}
};
api.unsubscribe = function (event) {
if (events.hasOwnProperty(event.name)) {
events[event.name].splice(events[event.name].indexOf(event), 1);
if (events[event.name].length == 0) {
delete events[event.name];
}
}
};
return api;
});
Now all you have to do is subscribe or publish events. The unsubscribe will take place automatically (when the $scope is destroyed):
$scope.$bus.subscribe({
name: 'test', callback: function (data) {
console.log(data);
}
});
And later on publish an event:
$scope.$bus.publish('test', {name: "publishing event!"});
An important point to make is that the events themselves are subscribed to each individual $scope and not on the $rootScope. That is how you "know" which $scope to release.
I think it answers your question. With that in mind, you can obviously make this mechanism much sophisticated (such as controller event listener released when a view routed, unsubscribe automatically only to certain events, etc.).
Good luck!
** This solution is taken form Here which uses a different bus framework (other then that it is the same).

Service to call and update angular controller $scope from outside of controller?

controller function:
$scope.init = function () {
Words.get('init', $scope.randNum)
.error(function (data) {
console.log('init error: ' + data.message);
})
.success(function (data) {
$scope.board = data.settings.board;
$scope.tray = data.tray;
$scope.scores = data.pointsPerLetter;
$scope.totalScore = data.score.total;
console.log('init: ' + $scope.tray);
})
}
and my service:
angular.module('wordService', [])
.factory('Words', function ($http) {
var id;
return {
get: function (call, num) {
id = num;
return $http.get('http://xxxxx');
},
send: function (call, data) {
console.log('send: ' + data)
return $http.post('http://xxxxx' + call, data);
}
}
});
Now instead of ngAccess = angular.element(document.getElementById('ws')).scope();
to call ngAccess.init() or $scope.init
How would I add this call to a service and thus call it when needed while still updating the scope within the controller? The reason the above will not work is that I am using browserify and I dont yet have access to the scope.
Scenario: I need to be able to click a button and call a function that updates the scope.
Caveat: the button is created and added to a canvas. (shouldnt matter as I still have the click calls etc).
As always thanks in advance!
Move the data object into the service and assign a reference to a controller scope variable...
Your factory might look like:
.factory('Words', function ($http) {
var id;
var results = {};
var get = function (call, num) {
id = num;
return $http.get('http://xxxxx').then(function(response){
results.board = response.data.settings.board;
results.tray = response.data.tray;
results.scores = response.data.pointsPerLetter;
results.totalScore = response.data.score.total;
};
};
var send = function (call, data) {
console.log('send: ' + data)
return $http.post('http://xxxxx' + call, data);
};
return {
get: get,
send: send,
results: results
}
});
While your controller would then look like:
.controller(function($scope, Words){
$scope.words = Words.results;
$scope.init = function () {
Words.get('init', $scope.randNum).then(function(){
console.log($scope.words); // should log the data you want
}, function(response){ console.log(response)});
};
// still calling from controller but you could from any component and still
// have the local scope variable update based on its assignment to the
// service object
$scope.init();
})
Note that I did modify your factory a bit more to use the revealing module pattern. This way, you can make internal calls to your get/set functions in addition to calls from other components.
Now you should be able to add a button virtually anywhere else in the app (ie doesn't need prototypical inheritance from your controller's scope). For example, this directive would make a call and update the results, which would reflect in the controller scope variable
.directive('update', function(Words){
return function(scope) {
scope.update = function(){
Words.get('update', 'somevalue')
}
}
})
where it is declared in the view like this:
<button update ng-click="update()">Update</button>

Backbone.js, cannot set context on a callback

Ok, so I am working on a method to override the fetch method on a model. I want to be able to pass it a list of URL's and have it do a fetch on each one, apply some processing to the results, then update its own attributes when they have all completed. Here's the basic design:
A Parent "wrapper" Model called AllVenues has a custom fetch function which reads a list of URL's it is given when it is instantiated
For each URL, it creates a Child Model and calls fetch on it specifying that URL as well as a success callback.
The AllVenues instance also has a property progress which it needs to update inside the success callback, so that it will know when all Child fetch's are complete.
And that's the part I'm having problems with. When the Child Model fetch completes, the success callback has no context of the Parent Model which originally called it. I've kind of hacked it because I have access to the Module and have stored the Parent Model in a variable, but this doesn't seem right to me. The Parent Model executed the Child's fetch so it should be able to pass the context along somehow. I don't want to hardcode the reference in there.
TL;DR
Here's my jsFiddle illustrating the problem. The interesting part starts on line 13. http://jsfiddle.net/tonicboy/64XpZ/5/
The full code:
// Define the app and a region to show content
// -------------------------------------------
var App = new Marionette.Application();
App.addRegions({
"mainRegion": "#main"
});
App.module("SampleModule", function (Mod, App, Backbone, Marionette, $, _) {
var MainView = Marionette.ItemView.extend({
template: "#sample-template"
});
var AllVenues = Backbone.Model.extend({
progress: 0,
join: function (model) {
this.progress++;
// do some processing of each model
if (this.progress === this.urls.length) this.finish();
},
finish: function() {
// do something when all models have completed
this.progress = 0;
console.log("FINISHED!");
},
fetch: function() {
successCallback = function(model) {
console.log("Returning from the fetch for a model");
Mod.controller.model.join(model);
};
_.bind(successCallback, this);
$.each(this.urls, function(key, val) {
var venue = new Backbone.Model();
venue.url = val;
venue.fetch({
success: successCallback
});
});
}
});
var Venue = Backbone.Model.extend({
toJSON: function () {
return _.clone(this.attributes.response);
}
});
var Controller = Marionette.Controller.extend({
initialize: function (options) {
this.region = options.region;
this.model = options.model;
this.listenTo(this.model, 'change', this.renderRegion);
},
show: function () {
this.model.fetch();
},
renderRegion: function () {
var view = new MainView({
model: this.model
});
this.region.show(view);
}
});
Mod.addInitializer(function () {
var allVenues = new AllVenues();
allVenues.urls = [
'https://api.foursquare.com/v2/venues/4a27485af964a52071911fe3?oauth_token=EWTYUCTSZDBOVTYZQ3Z01E54HMDYEPZMWOC0AKLVFRBIEXV4&v=20130811',
'https://api.foursquare.com/v2/venues/4afc4d3bf964a520512122e3?oauth_token=EWTYUCTSZDBOVTYZQ3Z01E54HMDYEPZMWOC0AKLVFRBIEXV4&v=20130811',
'https://api.foursquare.com/v2/venues/49cfde17f964a520d85a1fe3?oauth_token=EWTYUCTSZDBOVTYZQ3Z01E54HMDYEPZMWOC0AKLVFRBIEXV4&v=20130811'
];
Mod.controller = new Controller({
region: App.mainRegion,
model: allVenues
});
Mod.controller.show();
});
});
App.start();
I think you're misunderstanding how _.bind works. _.bind returns the bound function, it doesn't modify it in place. In truth, the documentation could be a bit clearer on this.
So this:
_.bind(successCallback, this);
is pointless as you're ignoring the bound function that _.bind is returning. I think you want to say this:
var successCallback = _.bind(function(model) {
console.log("Returning from the fetch for a model");
Mod.controller.model.join(model);
}, this);
Also note that I added a missing var, presumably you don't want successCallback to be global.

Categories