window.onload = function () {
'use strict'
var scope = {
increaseSprite: function () {
this.sprite++;
},
decreaseSprite: function () {
this.sprite--;
},
increaseCola: function () {
this.cola++;
},
decreaseCola: function () {
this.cola--;
},
cola: 0,
sprite: 0,
price: 3
}
function Scope() {
this.$$watchList = [];
}
Scope.prototype.$watch = function (name, getNewValue, listener) {
var watch = {
name: name,
getNewValue: getNewValue,
listener: listener || function () {}
};
this.$$watchList.push(watch);
}
Scope.prototype.$digest = function () {
var dirty = true;
var checkTimes = 0;
while(dirty){
dirty = this.$$digestOnce();
checkTimes++;
if(checkTimes > 10 && true){
throw new Error("检测超过10次");
}
};
}
Scope.prototype.$$digestOnce = function () {
var dirty;
var list = this.$$watchList;
for(var i = 0, l = list.length; i <l; i++){
var watch = list[i];
var newValue = watch.getNewValue();
var oldValue = watch.last;
if(newValue !== oldValue){
watch.listener(newValue, oldValue);
dirty = true;
}else{
dirty = false;
}
watch.last = newValue;
}
return dirty;
}
var $scope = new Scope();
$scope.$watch('sprite',function () {
$scope.sprite = scope.sprite;
return $scope[this.name];
},function (newValue, oldValue) {
console.log("sprite: newValue:" + newValue + '-------' + "oldValue" + oldValue);
});
$scope.$watch('cola',function () {
$scope.cola = scope.cola;
return $scope[this.name];
},function (newValue, oldValue) {
console.log("cola: newValue:" + newValue + '-------' + "oldValue" + oldValue);
});
$scope.$watch('sum',function () {
$scope.sum = (scope.cola + scope.sprite)*scope.price;
return $scope[this.name];
},function (newValue, oldValue) {
console.log("sum: newValue:" + newValue + '-------' + "oldValue" + oldValue);
});
function bind() {
var list = document.querySelectorAll('[ng-click]');
for(var i = 0, l = list.length; i < l; i++){
list[i].onclick = (function () {
return function () {
var func = this.getAttribute('ng-click');
scope[func]();
apply();
}
})()
}
}
function apply() {
$scope.$digest();
var list = document.querySelectorAll('[ng-bind]');
for(var i = 0, l = list.length; i < l; i++){
var bindData = list[i].getAttribute('ng-bind');
list[i].innerHTML = $scope[bindData];
}
}
bind();
apply();
}