Skip to content

Instantly share code, notes, and snippets.

@robbiemu
Last active August 24, 2016 11:11
Show Gist options
  • Save robbiemu/d180e786740667b03edd93337ec34a9a to your computer and use it in GitHub Desktop.
Save robbiemu/d180e786740667b03edd93337ec34a9a to your computer and use it in GitHub Desktop.
I ran into this with a test project .. I had started designing functions in the controller and later realized they should be in a service.
I was manipulating the $scope, a variable from the context, and migrating the functions would not be as simple as passing in scope, I had
to rewrite the returns as well.. so rather than do that, I wanted to write a wrapper that allowed me to transparently move the functions.
Since it didn't work right away, I ended up developing it from a model first. This is the model.
You can imagine that at first, adder was in the controller, and calls represents the changes to $scope.
Service = (function() {
return {
body: function(){
var s = {}
const controller_wrapper = function (f) {
return function () {
s = Array.prototype.shift.apply(arguments)
let r = f.apply(this, arguments)
return {
$scope: s,
return: r
}
}
}
return {
adder: controller_wrapper(function (a, b) {
s.calls.push([a, b])
return a + b
})
}
}
}
})()
Controller = (function() {
return {
scope: {},
body: function(Service, $scope=this.scope){
this.Service = Service
const service_wrapper = function(fun) {
return function() {
[].splice.call(arguments, 0,0, $scope);
var r = fun.apply(this, arguments)
if(r !== undefined) {
if ((typeof r === 'object') && ('$scope' in r)) {
$scope = r.$scope
return r.return
} else {
return r
}
}
}
}
$scope.calls = []
$scope.test = service_wrapper(this.Service.adder)
}
}
})()
Controller.body(Service.body())
Controller.scope.test(1,2)
console.log(JSON.stringify(Controller.scope.calls))
console.log(Controller.scope.test(3,4))
console.log(JSON.stringify(Controller.scope.calls))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment