簡體   English   中英

在Backbone中調用超類方法

[英]Calling super class method in Backbone

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;
   }
});

為什么上面的代碼不起作用? 為什么我無法在DerivedView中調用someFunction? 有沒有辦法實現這個目標?

我正在使用Backbone最新版本。

當你這樣做:

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);
   }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM