在主干中调用超类方法

Calling super class method in Backbone

本文关键字:超类 类方法 调用      更新时间:2023-09-26
var BaseView = Backbone.View.extend({
    localizedTemplate : function (element) {
        template = _.template(element.html());
        return function (data) {
            return template($.extend({}, data, resource));
        };
    }
});
var DerivedView = BaseView.extend({
   initialize: function (options) {
       this.model = options.model;
       this.template = function () {
         return this.localizedTemplate($("#someTemplate"));
       };
   },
   render: function () {
       var output = this.template(this.model.toJSON());
       this.$el.append(output);
       return this;
   }
});

为什么上面的代码不起作用? 为什么我无法在派生视图中调用 someFunction? 有什么方法可以实现这一点吗?

我正在使用骨干最新版本。

当你这样做时:

this.template = function () {
    return this.localizedTemplate($("#someTemplate"));
};

您正在为this.template 分配一个函数。请注意,localizedTemplate还返回一个函数:

return function (data) {
    return template($.extend({}, data, resource));
};

这意味着this.template是一个返回函数的函数,第二个函数是希望this.model.toJSON()作为参数的函数。

您正在执行此操作:

var output = this.template(this.model.toJSON());

this.template 中的函数忽略其参数并返回一个函数,该函数将剩下以下函数:

function () {
    return this.localizedTemplate($("#someTemplate"));
}

output.此时您可能认为output是一块 HTML,因此您将其交给append

this.$el.append(output);

但是output是一个函数,当以函数作为参数调用时,append做什么? jQuery像这样调用该函数:

函数(索引,html(
类型:函数((
返回 HTML 字符串、DOM 元素或 jQuery 对象的函数,以插入匹配元素集中每个元素的末尾。接收元素在集合中的索引位置和元素的旧 HTML 值作为参数。在函数中,this 是指集合中的当前元素。

因此,output函数将由jQuery的append调用,append将提供编译后的模板函数无法理解的参数。结果是一大堆混乱。

如果你真的想做这样的事情,那么你需要自己调用所有函数,以便你可以把正确的参数放在正确的位置:

var output = this.template()(this.model.toJSON());
// -----------------------^^

演示:http://jsfiddle.net/ambiguous/YyJLR/

或者更好的是,根本不用打扰所有额外的包装器。在视图initialize中这样说:

this.template = this.localizedTemplate($("#someTemplate"));

然后在render

var output = this.template(this.model.toJSON());

演示:http://jsfiddle.net/ambiguous/BQjhS/

另请注意,您不需要this.model = options.model ,视图构造函数将为您执行此操作:

有几个特殊选项,如果传递,将直接附加到视图:modelcollectionelidclassNametagNameattributes

var DerivedView = BaseView.extend({
   someVariable: function(someData) {
      return this.someFunction(someData);
   }
});