Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private-like properties in models or views of Backbone.js

Is it possible to have private properties in a model? Like the locally declared variables in a (constructor) function, not attached to this, but declared locally and visible only by whatever is defined in the (constructor)function. Example without BB View:

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
  ...
}

Note that internalInput is not accessible to outside world and aModel is also not accessible (through MyView at least). So if I want to use Backbone.View to implement the above MyView, how would i do it and keep $internalInput 'private'?

like image 752
Paralife Avatar asked Jan 19 '12 11:01

Paralife


2 Answers

You should be able to achieve private data by passing an IIFE to extend when defining your Backbone objects, rather than just a plain object. For example:

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

  return {
    bar: function () {
      console.log(foo);
    }
  };
})());
like image 155
Jimmy Avatar answered Nov 20 '22 00:11

Jimmy


You'd better off with

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

            this.getValue = function ()
            {
                return _value;
            };
            this.setValue = function (value)
            {
                _value = value;
            };
        }
    });
like image 41
Marble Daemon Avatar answered Nov 19 '22 23:11

Marble Daemon