Backbone.js的模型或视图中类似私有的属性

Par*_*ife 6 javascript private backbone.js

是否有可能在模型中拥有私有属性?就像(构造函数)函数中的本地声明的变量一样,没有附加到this,但只在(构造函数)函数中定义的任何内容声明为本地和可见.没有BB视图的示例:

function MyView(aModel){

  var $internalInput = $('<input>');

  this.render: function($where){
     $internalInput.val(aModel.get('SomeProperty'));
     $where.append($('<div class="inputWraper">').append($internalInput));
  };
  this.toggleReadonly: function() {
    toggle $internalInputs readonly attribute
  }
  ...
  + Code to bind input.val to some aModel property(ies) and setup events
  ...
}
Run Code Online (Sandbox Code Playgroud)

请注意, internalInput外部世界无法访问,aModel也无法访问(至少通过MyView).所以如果我想使用Backbone.View来实现上面的MyView,我该如何做并保持$ internalInput'private'?

Jim*_*dra 10

您应该能够通过extend在定义Backbone对象时传递IIFE来实现私有数据,而不仅仅是普通对象.例如:

var Thing = Backbone.Model.extend((function () {
  var foo = "Private data!";

  return {
    bar: function () {
      console.log(foo);
    }
  };
})());
Run Code Online (Sandbox Code Playgroud)

  • 这会给你更类似于私有静态属性的东西.如果您正在寻找模拟私有实例属性(如OP的var-in-constructor技术),那么您将被共享状态抛出,这会让您失望. (11认同)