简体   繁体   English

子级骨干视图如何在不将整个“ this”作为父类传递的情况下访问其父视图的特定属性

[英]How can a child backbone view get access to its parent view specific properties without passing whole 'this' as parent

I have a backbone parent view 我有骨干的父母观点

var ParentView = Backbone.View.extend({
  a : 'apple',
  b : 'boy',
  c : 'cat',
  changingA : function() {
     this.a = 'Ami'
   },
  createChild = function() {
      new ChildView({a : this.a});
   }
});

and a child view 和儿童观

var ChildView = Backbone.View.extend({
   intialize : function(args) {
     this.aa = args.a;
   },

   someOperation : function() {
      console.log(this.aa);  // this is not the current 'a' value of parent.
         //here i always get 'apple' even if i change the value of 'a' in parent
    }
});

How can i make sure this.aa in child always get the current available value in parent view. 我如何确保孩子中的this.aa始终在父视图中获得当前可用值。

what is the main reason behind that? 这背后的主要原因是什么? I am passing 'reference' of 'a' to child view. 我将“ a”的“引用”传递给子视图。 So child view should always have the updated value from parent. 因此,子视图应始终具有父视图的更新值。 But why this do not happens?? 但是为什么这种情况不会发生?

I also do not want to pass the whole 'this' parameter as parent to child 我也不想将整个“ this”参数作为父级传递给子级

You have to create an object and share the reference between parent and child 您必须创建一个对象并在父级和子级之间共享引用

var ParentView = Backbone.View.extend({
  obj: {
    a : 'apple',
    b : 'boy',
    c : 'cat'
  },
  changingA : function() {
     this.obj.a = 'Ami'
   },
  createChild = function() {
      new ChildView({obj : this.obj});
   }
});

var ChildView = Backbone.View.extend({
   intialize : function(args) {
     this.obj = args.obj;
   },

   someOperation : function() {
      console.log(this.obj.a);  // this is not the current 'a' value of parent.
         //here i always get 'Apple' even if i change the value of 'a' in parent
    }
});

But be careful, this object reference is also shared between instances of "ParentView", to bypass this problem, create the obj reference inside constructor. 但是要小心,该对象引用也在“ ParentView”的实例之间共享,为了绕过此问题,请在构造函数内部创建obj引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM