在子视图中覆盖自定义属性

时间:2016-10-27 05:56:11

标签: javascript backbone.js

我有一个基本视图和一个子视图,使用名为" menu"的属性扩展基本视图。我尝试了以下内容。

var baseView=Backbone.View.extend({
    menu:"#base-menu",
    initialize:function(){
         //some code
    },
    render:function(){
        console.log(this.menu);
    }
});
var childView=baseView.extend({
    initialize:function(){
        baseView.prototype.initialize.apply(this);
        this.menu="#child-menu";
    }
});

但是childView.render()未输出#child-menu,它仅设置为#base-menu。为什么以及如何让孩子一套?

注意:有多个子视图。



var baseView = Backbone.View.extend({
  menu: "#base-menu",
  initialize: function() {
    console.log(this.menu);
  },

});

var firstView = baseView.extend({
  initialize: function() {
    baseView.prototype.initialize.apply(this, arguments);
    this.menu = "#child-menu";
    console.log(this.menu);

  }
});

var firstViewInstance = new firstView();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

覆盖父级&#34;类&#34;的属性使用Backbone&#39; extend,只需再次设置该属性:

var BaseView = Backbone.View.extend({
    menu: "#base-menu",
    initialize: function() {
        console.log("Base", this.menu);
    },

});

var ChildView =  BaseView.extend({
    menu: "#child-menu", // override directly here
    initialize : function(options) {
        ChildView.__super__.initialize.apply(this, arguments);
        console.log("Child", this.menu);
    }
});

创建子视图:

var child = new ChildView();

应输出

Base #base-menu
Child #child-menu