首页 > Backbone.js开发中this.render()与this.render的奇怪现象?

Backbone.js开发中this.render()与this.render的奇怪现象?

var view= Backbone.View.extend({
    el: 'body',
    template: doT.template(tpl),
    initialize: function () {
         this.model = new Model();
         this.model.on('sync',this.render,this);
         //this.model.on('sync',this.render(),this);
         this.model.fetch();
    },

    render: function (e) {
            console.log(this.model.toJSON())
        },
    });
    return view;

this.model.on('sync',this.render(),this);


this.render,this.render()是因为backbone的机制照成的么,一个是数据回来时执行,一个是立即执行;
这个有什么知识点


this.model.on('sync',this.render,this);//类似于 
this.model.on('sync',function(){
    return '我是回调'
},this)

this.model.on('sync',this.render(),this);//类似于
this.model.on('sync','我是回调',this);

var foo;

foo = function() {
  return 1;
};

console.log('foo:', foo);

console.log('foo():', foo());

不是backbone的机制,是javascript就是这样的啊,函数名后面加括弧就是函数调用。
this.model.on('sync', this.render(), this); 这里你使用了this.render()调用函数,就会立刻执行,然后将这个函数的执行结果作为on函数的参数。


首先要搞清楚下面语句的语义
this.model.on('sync',this.render,this);
在model的sync事件发生时,执行render函数
也就是将render函数添加到sync事件的执行序列中,等待sync事件的发生

这个问题也就是:

var dom=document.getElementById('submitBut');
//声明一个函数
var clickHandler=function(){
    ...
}
//把这个函数注册到click事件的回调序列中
//click事件触发后,这个函数会执行,即执行 clickHandler(); 语句
dom.addEventListener('click', clickHandler,false);
【热门文章】
【热门文章】