【问题标题】:Call a parent view's function in Marionette.js在 Marionette.js 中调用父视图的函数
【发布时间】:2014-06-04 01:06:04
【问题描述】:

在 Marionette 中,如何在视图的父对象上调用同名函数而不覆盖原始函数?

例如:

var someView = new Backbone.Marionette.ItemView.extend({
    onRender: function () {
        console.log('foo');
    }
});

var anotherView = someView.extend({
    onRender: function () {

        // call someView's original onRender function

        console.log('bar');
    }
});

anotherView.render();

导致控制台输出:

foo
bar

【问题讨论】:

  • 所以你不是指父视图(在树中),而是你继承的super 视图?

标签: javascript backbone.js marionette


【解决方案1】:

可以使用__super__,由extend设置:

var anotherView = someView.extend({
    onRender: function () {
        this.__super__.onRender.call(this);
        console.log('bar');
    }
});

或直接引用您要在实例上应用的方法:

var anotherView = someView.extend({
    onRender: function () {
        someView.prototype.onRender.call(this);
        console.log('bar');
    }
});

有关详细信息,请参阅Javascript Class Inheritance For Functions 和 what .call() does。

【讨论】:

  • 这正是我想要的。谢谢。
  • 支持你的第二个例子,在 Marionette 2.0.0 中,至少第一个例子说 undefined for super
  • 这些都不能在 Marionette 4.1.2 中工作。不得不使用这个:Object.getPrototypeOf(this).onRender.call(this);
  • @Briguy37 你在第二个问题上遇到了什么错误?尽管这个答案已经 8 岁了,Superclass.prototype.method.call 是一个永恒的解决方案,也适用于 ES6 类。 Marionette 是否不再使用标准原型继承?
  • @Bergi this.prototype 是 undefined 当我在 Chrome devtools 中调试它作为手表时,但 [[Prototype]] 属性显示在它上面,并且可以通过我之前评论中的 Object.getPrototypeOf 访问.
猜你喜欢
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多