Skip to content

Instantly share code, notes, and snippets.

@marcofiset
Created November 12, 2014 22:33
Show Gist options
  • Save marcofiset/e46e827594eef6ce79ff to your computer and use it in GitHub Desktop.
Save marcofiset/e46e827594eef6ce79ff to your computer and use it in GitHub Desktop.
Very simple and naive implementation of AngularJS, from https://www.youtube.com/watch?v=Mk2WwSxK218
function Scope() {
var self = this;
self.$$watchers = [];
self.$watch = function(watcherFn, listenerFn) {
self.$$watchers.push({
watcherFn: watcherFn,
listenerFn: listenerFn
});
};
self.$digest = function() {
self.$$watchers.forEach(function(watcher) {
var oldValue = watcher.oldValue;
var newValue = watcher.watcherFn();
if (newValue !== oldValue)
watcher.listenerFn(newValue, oldValue);
watcher.oldValue = newValue;
});
};
self.$apply = function(fn) {
try {
fn();
} finally {
self.$digest();
}
};
}
var $$directives = {
'ng-bind': function(element, $scope) {
var binding = element.attributes['ng-bind'].value;
$scope.$watch(function() {
return $scope[binding];
}, function(newValue) {
element.innerHTML = newValue;
});
},
'ng-model': function(element, $scope) {
var binding = element.attributes['ng-model'].value;
$scope.$watch(function() {
return $scope[binding];
}, function(newValue) {
if (element !== document.activeElement)
element.value = newValue;
});
element.addEventListener('keyup', function() {
$scope.$apply(function() {
$scope[binding] = element.value;
});
});
}
};
var $compile = function(element, $scope) {
Array.prototype.forEach.call(element.children, function(child) {
$compile(child, $scope);
});
Array.prototype.forEach.call(element.attributes, function(attr) {
var directive = $$directives[attr.name];
if (directive)
directive(element, $scope);
});
};
var $rootScope = new Scope();
$compile(document.body, $rootScope);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello Angular</title>
</head>
<body>
<h1 ng-bind="message"></h1>
<input type="text" ng-model="message"><br>
<input type="text" ng-model="message">
<p ng-bind="message"></p>
<script type="text/javascript" src="angular.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment