Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Toy AngularJS clone
(function () {
'use strict';
var $rootScope;
var directives;
var Scope = (function () {
/**
* @constructor
*/
function Scope() {
this.$$watchers = [];
}
/**
* @param {Function} watchExpression
* @param {Function} listener
*/
Scope.prototype.$watch = function (watchExpression, listener) {
var oldValue;
var newValue;
this.$$watchers.push(function () {
newValue = watchExpression();
if (newValue !== oldValue) {
listener(newValue, oldValue);
oldValue = newValue;
}
});
};
Scope.prototype.$digest = function () {
var i;
for (i = 0; i < this.$$watchers.length; i++) {
this.$$watchers[i]();
}
};
/**
* @param {Function} fn
*/
Scope.prototype.$apply = function (fn) {
try {
fn.call(this);
} finally {
this.$digest();
}
};
return Scope;
})();
directives = {
/**
* @param {Scope} $scope
* @param {Element} iElement
* @param {Array.<Attr>} iAttrs
*/
'ng-bind': function ngBindLinkFn($scope, iElement, iAttrs) {
$scope.$watch(function () {
return $scope[iElement.getAttribute('ng-bind')];
}, function (value) {
iElement.textContent = value;
});
},
/**
* @param {Scope} $scope
* @param {HTMLInputElement} iElement
* @param {Array.<Attr>} iAttrs
*/
'ng-model': function ngModelLinkFn($scope, iElement, iAttrs) {
iElement.addEventListener('input', function () {
$scope.$apply(function () {
$scope[iElement.getAttribute('ng-model')] = iElement.value;
});
});
$scope.$watch(function () {
return $scope[iElement.getAttribute('ng-model')];
}, function (value) {
iElement.value = value;
});
}
};
/**
* @param {Node} element
*/
function $compile(element) {
var i;
var directive;
var attrs;
if (element.nodeType === 3 || element.nodeType === 8) {
return;
}
for (i = 0; (attrs = element.attributes) && i < attrs.length; i++) {
directive = directives[attrs[i].name];
if (directive) {
directive($rootScope, element, attrs);
}
}
for (i = 0; i < element.childNodes.length; i++) {
$compile(element.childNodes[i]);
}
}
document.addEventListener('DOMContentLoaded', function () {
$rootScope = new Scope();
$compile(document);
$rootScope.something = 'Two-way data binding is up!';
$rootScope.$digest();
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.