Skip to content

Commit

Permalink
feat: <refactoring code>
Browse files Browse the repository at this point in the history
  • Loading branch information
Jake.Zheng authored and Jake.Zheng committed Sep 25, 2018
1 parent 2d72846 commit 5b3e20e
Show file tree
Hide file tree
Showing 14 changed files with 99 additions and 142 deletions.
18 changes: 15 additions & 3 deletions demo/components/comp7.html
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
<uku-component>
<template>
<ul>
<li uku-repeat="num in cc.totalNumber">
{{num}}
<li uku-repeat="num in cc.totalNumber" uku-class=" num === cc.currentNumber?'normal red':'normal'">
<a uku-onclick="cc.change(num)">{{num}}</a>
</li>
</ul>
</template>
<script>
this.totalNumber = 100;
this.totalNumber = 1000;
this.currentNumber = 1;
this.classFunction = function(n){
if(this.currentNumber === n){
return 'normal red'
}else{
return 'normal';
}
}
this.change = function(e, n){
this.currentNumber = n;
console.log(this.currentNumber);
}
</script>
</uku-component>
12 changes: 9 additions & 3 deletions demo/native.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@
p{
color:green;
}
.red{
color: red;
}
.normal{
border: 1px solid black;
}
</style>
<script src="../dist/uku.js"></script>
</head>
Expand All @@ -15,11 +21,11 @@
<!-- <my-comp5 uku-item-value="99 + myCtrl.number" uku-item-value2="myCtrl.show"></my-comp5> -->
<!-- <my-comp6 id="comp6" uku-current-state="myCtrl.loginState"></my-comp6> -->
<my-comp7></my-comp7>
<button uku-onclick="myCtrl.switchState()">change state</button>
<button uku-onclick="$myCtrl.switchState()">change state</button>
</body>
<script>
var uku = new Ukulele();
uku.registerController('myCtrl',new MyCtrl(uku));
uku.registerController('$myCtrl',new MyCtrl(uku));

//uku.registerComponent('my-comp5','components/comp5.html');
//uku.registerComponent('my-comp6','components/comp6.html');
Expand Down Expand Up @@ -52,7 +58,7 @@
this.loginUser = {username:"momoko"};
//this.options = [{'name':'AAA',value:'aaa'},{'name':'BBB',value:'bbb'}];

uku.refresh('myCtrl');
uku.refresh('$myCtrl');

}
//this.items = [{'name':'AAA',value:'aaa'},{'name':'BBB',value:'bbb'}];
Expand Down
2 changes: 1 addition & 1 deletion dist/uku.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/uku.js.map

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions src/core/Analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class Analyzer extends EventEmitter {
this.searchComponent(ele).then((element) => {
this.searchExpression(element);
this.searchUkuAttribute(element);
this.defMgr.copyAllController();
//this.defMgr.copyAllController();
if (this.hasListener(Analyzer.ANALYIZE_COMPLETED)) {
this.dispatchEvent(new UkuEvent(Analyzer.ANALYIZE_COMPLETED, element));
}
Expand Down Expand Up @@ -133,7 +133,8 @@ export class Analyzer extends EventEmitter {
}

private async dealWithComponent(tag, template, Clazz, attrs): Promise<any> {
let randomAlias = 'cc_' + Math.floor(10000 * Math.random()).toString();
let time = new Date().getTime();
let randomAlias = 'cc_' + Math.floor(time * Math.random()).toString();
//should consider white space between characters
template = template.replace(new RegExp("\'cc\\.", 'gm'), "'" + randomAlias + '.');
template = template.replace(new RegExp('"cc\\.', 'gm'), '"' + randomAlias + '.');
Expand Down Expand Up @@ -299,7 +300,7 @@ export class Analyzer extends EventEmitter {
EventListener.addEventListener(element, eventNameInListener, (event) => {
let alias_list = [];
controllerModels.forEach(controllerModel => {
this.defMgr.copyControllerInstance(controllerModel.controllerInstance, controllerModels.alias);
//this.defMgr.copyControllerInstance(controllerModel.controllerInstance, controllerModels.alias);
alias_list.push(controllerModel.alias);
});

Expand Down
73 changes: 31 additions & 42 deletions src/core/DefinitionManager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { ObjectUtil } from "../util/ObjectUtil";
import { Ajax } from "../extend/Ajax";
import { ControllerModel } from "../model/ControllerModel";
import { ComponentModel } from "../model/ComponentModel";
Expand Down Expand Up @@ -54,20 +53,6 @@ export class DefinitionManager {
return this.copyControllers;
}

copyAllController(): void {
for (let alias in this.controllersDefinition) {
let controllerModel = this.controllersDefinition[alias];
let controller = controllerModel.controllerInstance;
this.copyControllerInstance(controller, alias);
}
}

copyControllerInstance(controller: Object, alias: string): void {
let previousCtrlInst = ObjectUtil.deepClone(controller);
delete this.copyControllers[alias];
this.copyControllers[alias] = previousCtrlInst;
}

addControllerDefinition(instanceName: string, controllerInst): void {
let controllerModel = new ControllerModel(instanceName, controllerInst);
controllerInst._alias = instanceName;
Expand Down Expand Up @@ -129,7 +114,37 @@ export class DefinitionManager {


getControllerModelByName(expression: string): ControllerModel[] {
return this.getBoundControllerModelByName(expression);
let arr = [];
let normalReg = /\$\w+\./g;
let normals = expression.match(normalReg);
if(normals){
normals.forEach( matchAlias => {
matchAlias = matchAlias.substr(0,matchAlias.length-1);
let controllerModel: ControllerModel = this.controllersDefinition[matchAlias];
arr.push(controllerModel);
});
}

let ccReg = /cc\_\w*\./g;
let ccs = expression.match(ccReg);
if(ccs){
ccs.forEach( ccAlias => {
ccAlias = ccAlias.substr(0,ccAlias.length-1);
let controllerModel: ControllerModel = this.controllersDefinition[ccAlias];
arr.push(controllerModel);
});
}

let repeatReg = /repeatItem\_\w*\$/g;
let repeats = expression.match(repeatReg);
if(repeats){
repeats.forEach( repeatAlias => {
//repeatAlias = repeatAlias.substr(0,repeatAlias.length-1);
let controllerModel: ControllerModel = this.controllersDefinition[repeatAlias];
arr.push(controllerModel);
});
}
return arr;
};


Expand All @@ -143,32 +158,6 @@ export class DefinitionManager {
return UkuleleUtil.getFinalValue(controllers, expression);
};

private getBoundControllerModelByName(attrName: string): ControllerModel[] {
let arr = [];
let alias_list: string[];
let instanceNames: string[];
if (attrName.search('parent.') !== -1) {
let parentDefinitionManager = this.uku.parentUku._internal_getDefinitionManager();
alias_list = Object.keys(parentDefinitionManager.controllersDefinition);
instanceNames = UkuleleUtil.getBoundModelInstantNames(alias_list, attrName);

instanceNames.forEach(instanceName => {
let controllerModel: ControllerModel = parentDefinitionManager.controllersDefinition[instanceName];
arr.push(controllerModel);
});
} else {
alias_list = Object.keys(this.controllersDefinition);
instanceNames = UkuleleUtil.getBoundModelInstantNames(alias_list, attrName);

instanceNames.forEach(instanceName => {
let controllerModel: ControllerModel = this.controllersDefinition[instanceName];
arr.push(controllerModel);
});
}

return arr;
}

private async analyizeComponent(tag: string, config: ComponentConfiguration): Promise<void> {
let deps: Array<string> = config.dependentScripts;
let self: DefinitionManager = this;
Expand Down
21 changes: 11 additions & 10 deletions src/core/DirtyChecker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {Event} from "./Event";
export class DirtyChecker{
private uku:IUkulele;
private defMgr;
private oldValueCache = {};
constructor(_uku:IUkulele){
this.uku = _uku;
this.defMgr = this.uku._internal_getDefinitionManager();
Expand All @@ -33,26 +34,25 @@ export class DirtyChecker{
function watchController(alias:string) {
let controllerModel:ControllerModel = _this.defMgr.getControllersDefinition()[alias];
if (!controllerModel) {
if (_this.uku.parentUku) {
_this.uku.parentUku.refresh(alias);
}
return;
}
let controller:Object = controllerModel.controllerInstance;
let previousCtrlModel:ControllerModel = _this.defMgr.getCopyControllers()[alias];
//let previousCtrlModel:ControllerModel = _this.defMgr.getCopyControllers()[alias];
if(!_this.oldValueCache[alias]){
_this.oldValueCache[alias] = {};
}
let oldValueMap = _this.oldValueCache[alias];
let changedElementCount = 0;
for (let i = 0; i < controllerModel.boundItems.length; i++) {
let boundItem:BoundItemBase = controllerModel.boundItems[i] as BoundItemBase;
let attrName:string = boundItem.attributeName;
// if(attrName.search('parent.') > -1){
// return;
// }
if (previousCtrlModel) {

if (oldValueMap) {
if (boundItem.hasOwnProperty('ukuTag') && boundItem['ukuTag'] === "selected") {
attrName = attrName.split("|")[0];
}
let finalValue = UkuleleUtil.getFinalValue( [controller], attrName);
let previousFinalValue = UkuleleUtil.getFinalValue([previousCtrlModel], attrName);
let previousFinalValue = oldValueMap[attrName];
if (!ObjectUtil.compare(previousFinalValue, finalValue)) {
attrName = boundItem.attributeName;
let changedBoundItems:Array<BoundItemBase> = controllerModel.getBoundItemsByName(attrName);
Expand All @@ -63,13 +63,14 @@ export class DirtyChecker{
changedBoundItem.render([controller]);
}
}
oldValueMap[attrName] = finalValue;
}
}
}
if(changedElementCount > 0 && _this.uku.hasListener(UkuEventType.REFRESH)){
_this.uku.dispatchEvent(new Event(UkuEventType.REFRESH));
}
_this.defMgr.copyControllerInstance(controller, alias);
//_this.defMgr.copyControllerInstance(controller, alias);
}
};
}
4 changes: 1 addition & 3 deletions src/core/IUkulele.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
import {IEventEmitter} from "./IEventEmitter";
import {DefinitionManager} from "./DefinitionManager";
export interface IUkulele extends IEventEmitter{

parentUku:IUkulele;


init();

handleElement(element, handleElementCompletedFunc);
Expand Down
15 changes: 14 additions & 1 deletion src/core/Ukulele.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,35 @@ import { Selector } from "../extend/Selector";
import { UkuEventType } from "./UkuEventType";
import { IUkulele } from "./IUkulele";
import { Event } from "./Event";
import { ControllerModel } from "../model/ControllerModel";

export let Ukulele = class Ukulele extends EventEmitter implements IUkulele {
private defMgr: DefinitionManager;
private dirtyChecker: DirtyChecker;
private promiseArray = [];
public parentUku: IUkulele;

private _childrenUku = {};
static INITIALIZED: string = 'initialized';
static REFRESH: string = 'refresh';
static HANDLE_ELEMENT_COMPLETED: string = "handle_element_completed";


public init(): void {
Promise.all(this.promiseArray).then(() => {
this.manageApplication();
});
}

public setChildrenUku(controllers, uku){
for(let cc of controllers){
let alias = cc._alias;
if(!this._childrenUku[alias]){
this._childrenUku[alias] = []
}
this._childrenUku[alias].push(uku);
}
}

public handleElement(element: HTMLElement, handleElementCompletedFunc: Function): void {
this.analyizeElement(element, (e) => {
this.dispatchEvent(new Event(UkuEventType.HANDLE_ELEMENT_COMPLETED, e));
Expand Down
23 changes: 11 additions & 12 deletions src/model/BoundItemRepeat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,31 +98,30 @@ export class BoundItemRepeat extends BoundItemBase{
}

let child:HTMLElement = (commentNode as HTMLElement).nextElementSibling as HTMLElement;
let time = new Date().getTime();
for (let j = 0; j < finalValue.length; j++) {
child.removeAttribute("uku-repeat");
var Uku_Clazz = (<any>this.uku).constructor;
let ukulele:IUkulele = new Uku_Clazz(); //new Ukulele();
ukulele.parentUku = this.uku;
let compDef = ukulele.parentUku._internal_getDefinitionManager().getComponentsDefinition();
let compPool = ukulele.parentUku._internal_getDefinitionManager().getComponentsPool();
ukulele._internal_getDefinitionManager().setComponentsDefinition(compDef);
ukulele._internal_getDefinitionManager().setComponentsPool(compPool);
let compDef = this.uku._internal_getDefinitionManager().getComponentsDefinition();
let compPool = this.uku._internal_getDefinitionManager().getComponentsPool();
this.uku._internal_getDefinitionManager().setComponentsDefinition(compDef);
this.uku._internal_getDefinitionManager().setComponentsPool(compPool);
let sibling:HTMLElement = child.nextSibling as HTMLElement;
let itemType = typeof finalValue[j];
let alias = "repeatItem_"+Math.floor(10000 * Math.random()).toString() + "_" + this.expression;
let alias = "repeatItem_"+Math.floor(time * Math.random()).toString() + "_" + this.expression + "$";
if(itemType === "object"){
ukulele.registerController(alias, finalValue[j]);
this.uku.registerController(alias, finalValue[j]);
}else {
ukulele.registerController(alias, {'value':finalValue[j]});
this.uku.registerController(alias, {'value':finalValue[j]});
alias = alias + ".value";
}
let pattern = new RegExp("\\b"+ this.expression + "(?!\\-|\\s|\\w|\\=)","gm");
//let pattern = new RegExp("\\b"+ this.expression + "(?!\\-|\\s|\\w|\\=)","gm");
let pattern = new RegExp(this.expression+"(?!\\w)","gm");
let newOuterHtml = child.outerHTML.replace(pattern,alias);
child.insertAdjacentHTML('afterend',newOuterHtml);
let newItemDom:HTMLElement = child.nextSibling as HTMLElement;
child.parentNode.removeChild(child);
child = newItemDom;
ukulele._internal_dealWithElement(child,(element)=>{
this.uku._internal_dealWithElement(child,(element)=>{
if (this.element.tagName === "OPTION") {
let expression = (this.parentElement as HTMLInputElement).getAttribute("uku-selected");
let tempArr = expression.split("|");
Expand Down
32 changes: 0 additions & 32 deletions src/util/ObjectUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,36 +75,4 @@ export class ObjectUtil {
}
return result;
}

static deepClone(obj: any): any {
let o: any;
let i: any;
let j: number;
if (typeof (obj) !== "object" || obj === null) {
return obj;
}
if (obj instanceof (Array)) {
o = [];
i = 0;
j = obj.length;
for (; i < j; i++) {
if (typeof (obj[i]) === "object" && obj[i] !== null) {
o[i] = ObjectUtil.deepClone(obj[i]);
} else {
o[i] = obj[i];
}
}
} else {
o = {};
for (i in obj) {
if (typeof (obj[i]) === "object" && obj[i] !== null && i !== "_dom") {
o[i] = ObjectUtil.deepClone(obj[i]);
} else {
o[i] = obj[i];
}
}
}

return o;
}
}
2 changes: 1 addition & 1 deletion src/util/UkuleleUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ export class UkuleleUtil {
let arr = [];
controller_alias_list.forEach(alias => {
let pattern = new RegExp("\\b" + alias, "gm");
console.count('getBoundModelInstantNames执行的次数');
if (expression.search(pattern) > -1) {
arr.push(alias);
}
Expand Down Expand Up @@ -166,7 +167,6 @@ export class UkuleleUtil {
static setFinalValue(object: Object, attrName: string, value: any) {
return (function () {
var tempScope = {};
attrName = attrName.replace('parent.', '');
tempScope[object['_alias']] = object;

let valueString;
Expand Down
Loading

0 comments on commit 5b3e20e

Please sign in to comment.