模块封装

1.什么是模块化?

模块化是一种处理复杂系统分解为更好的可管理模块的方式。解决一个复杂问题时自顶向下逐层把系统划分成若干模块的过程,有多种属性,分别反映其内部特性。

在程序中,代码封装成模块化,独立运行,可以在多个项目中使用。

2.为什么要封装成模块?

模块化用来分割,组织和打包软件。每个模块完成一个特定的子功能,所有的模块按某种方法组装起来,成为一个整体,完成整个系统所要求的功能。主要是封装完成之后,后面做项目用起来会很轻松,并且节约工作量和时间,减少错误以及代码的臃肿会影响代码的可读性。

3.怎么去封装成模块?

把单独的属性拿出来封装在一起,经过处理,在需要使用这个属性的地方抛出一个自定义事件,然后在这个模块里面去接收和处理,然后得到想要的结果。

4.在cocos-js中,对模块化的心得
①用自定义事件方法:只需要去在用的地方抛出事件传出数据,然后在模块里面接受处理就可以了,对封装的模块不会有大的改动。
②用回调传参的方法:在使用的地方调用封装的模块(类),传入数据,然后到模块里面去接受数据处理,再到前面传参的地方进行回调获得结果。整体和自定义事件大致相同,只是当数据过多时,各种调用会影响代码的可读性,并且在以后的项目中使用时需要重新传参和处理,容错率也极低。

例如:
var Ball = cc.Sprite.extend({
    direction:1,
    num:5,
    _touch:3,
    ctor:function () {
        this._super("res/shuimu.png");
        this.num = parseInt(2+Math.random()*3);
        this.setPosition(Math.random()*cc.winSize.width,Math.random()*cc.winSize.height);
        this.scheduleUpdate();
        var that = this;
        var listener = cc.EventListener.create({
            event:cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouches:true,  
            onTouchBegan:function(touch,event){
                var target = event.getCurrentTarget();   
                var pos  = touch.getLocation();    
                var s = target.getContentSize();    
                var rect = cc.rect(0,0, s.width, s.height);  
                var localPoint = target.convertToNodeSpace(pos);  
                if(cc.rectContainsPoint(rect,localPoint)){        
                    cc.log("被点击了");
                    that.setColor(cc.color(parseInt(Math.random()*255),parseInt(Math.random()*255),parseInt(Math.random()*255),255));
                    that.removeAll(target);
                    return true;
                }else {
                    return false;
                }
            }
        });
        cc.eventManager.addListener(listener,this);  
    },
    removeAll:function(object){
        this._touch--;
        if(this._touch <= 0 ){
            object.removeFromParent(true)
        }
    },
    update:function() {
        this.x += this.num * this.direction;
        if (this.x <= 0 || this.x > cc.winSize.width) {
            this.direction *= -1;                
            this.scaleX *= -1;                   
        }
    },
})

var HelloWorldScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
       // var a = 10;
       for(var i = 0;i<10;i++){
            this.addChild(new Ball());
        }
    }
});
this._super();调用这个类的父类的同名方法,没有父类的类不能调用this._super();
scheduleUpdate();该函数会每一帧都调用,调用的方法名为"update"
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值