Backbone.js的视图的传承。 `父this`分辨率 [英] backbone.js view inheritence. `this` resolution in parent

查看:140
本文介绍了Backbone.js的视图的传承。 `父this`分辨率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用视图的传承情况下,我的code看起来基本上是这样的:

I have a case that uses view inheritence, and my code looks essentially like:

parentView = Backbone.View.extend({
    events: {
        "some event": "business"
    },
    initialize: function(){
        _.bindAll(this);
    },
    business: function(e){
        ...
        this.someFunc && this.someFunc();
        ...
     }
});

childView = parentView.extend({
    events: {
        ...
    },
    constructor: function(){
       this.events = _.extend( {}, parentView.prototype.events, this.events );
       parentView.prototype.initialize.apply( this );
    },
    initialize: function(){
       _.bindAll(this);
    },
    someFunc: function(){
       ...
    }
});

更新:已移动 this.events 扩展到构造

在里面,并在父视图中的某些业务功能,如果存在的话,应该调用该函数。如果这个已正确设置为childView,那么 this.someFunc 应该存在。然而,这并不是说我遇到的行为。

My child view has someFunc in it, and during some business function in the parent view, it should call that function if it exists. If this is properly set to the childView, then this.someFunc should exist. This, however, is not the behaviour that I am experiencing.

初始化功能(父),这个确实设置为子视图。然而,当某些事件火灾中,商业函数调用这个设置为 parentView

During the initialize function (in the parent), this is indeed set to the child view. However, when some event fires, the business function is called with this set to parentView.

我敢肯定有一些简单的,我很想念,任何帮助是AP preciated。

I'm sure there is something simple that I am missing, and any help is appreciated.

推荐答案

你试过在初始化函数扩展 this.events 在构造函数,而不是?如果你这样做的初始化,你来得太晚了;为商业功能已经在构造函数中设置,将指向 parentView 事件代表团(见调用 this.delegateEvents(); 在Backbone.View的构造函数)

Have you tried extending this.events in the constructor, instead of in the initialize function? If you do this in initialize, you're too late; event delegation for the business function has already been setup in the constructor, and will point to parentView (see the call to this.delegateEvents(); in Backbone.View's constructor).

更新,其中一个工作示例:

Updated with a working example:

ParentView = Backbone.View.extend({
    name: 'ParentView',
    events: {
        "event": "business"
    },
    business: function(e){
        this.someFunc && this.someFunc();
    }
});

ChildView = ParentView.extend({
    name: 'ChildView',
    events: {
    },
    constructor: function(){
       this.events = _.extend( {}, ParentView.prototype.events, this.events );
       console.debug( this.events );
       ParentView.prototype.constructor.apply( this, arguments );
    },
    someFunc: function(){
        console.debug('someFunc; this.name=%s', this.name);
    }
});

child = new ChildView();
$( child.el ).trigger('event');
// logs 'this' in 'someFunc'; the name is 'ChildView'.

这篇关于Backbone.js的视图的传承。 `父this`分辨率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆