Quantcast
Channel: Cocos中文社区 - 最新帖子
Viewing all articles
Browse latest Browse all 495283

自己用creator一个月的心得,特贡献代码来了

$
0
0

bind函数的效率不高,还没有bind函数之前一般是用闭包来解决这类问题

var self = this;
var dataBinded = "this is a binded data";
script.setOnClickHandler(function(data){
    self.onClickBtn(dataBinded, data);
})

如果觉得这样的代码比较难看,可以像cocos2d-lua中提供的handler函数那样实现一个看起来比较优雅的接口,但是这样无法在设置回调的时候绑定参数(因为这种需求并不常见)

cc.handler = function(caller, callee){
    return function(){
        callee.apply(caller, arguments)
    }
}

script.setOnClickHandler(cc.handler(this, this.onClickBtn));

如果一定要在生成handler时绑定参数的话可以参考下面的代码

cc.handler = function(caller, callee){
    // 生成handler时传入的参数, 注意要移除前2个参数caller和callee
    var binded = Array.prototype.slice.call(arguments).splice(2);
    return function(){
        // 将生成handler时传入的参数和调用handler时传入的参数合并成一组参数, 然后执行handler
        callee.apply(caller, binded.concat(Array.prototype.slice.call(arguments)))
    }
}

Viewing all articles
Browse latest Browse all 495283

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>