Skip to content

Instantly share code, notes, and snippets.

@freizl
Last active December 19, 2015 11:09
Show Gist options
  • Save freizl/5945696 to your computer and use it in GitHub Desktop.
Save freizl/5945696 to your computer and use it in GitHub Desktop.
Two practices to extend Backbone model
var Parent = Backbone.Model.extend({
age : 3,
ref: []
});
var Child1 = Parent.extend(),
Child2 = Parent.extend();
var c1 = new Child1(),
c2 = new Child2();
c1.age = 10;
c1.ref.push(3);
c2.ref.push(4);
console.assert(c1.age !== c2.age, "age is not same");
console.assert(c1.ref !== c2.ref, "ref value is not name"); // Failure here !!!
var Parent = Backbone.Model.extend({
defaults: function () {
return {
age : 3,
ref: []
};
}});
var Child1 = Parent.extend({}),
Child2 = Parent.extend({});
var c1 = new Child1(),
c2 = new Child2();
c1.set('age', 10);
var xs = c1.get('ref');
xs.push(3);
c1.set('ref', xs);
var ys = c2.get('ref');
ys.push(4);
c2.set('ref', ys);
console.assert(c1.get('age') > 0);
console.assert(c2.get('age') > 0);
console.assert(c1.get('ref').length === 1);
console.assert(c2.get('ref').length === 1);
console.assert(c1.get('age') !== c2.get('age'), "age is not same");
console.assert(c1.get('ref') !== c2.get('ref'), "ref value is not name");
@beherca
Copy link

beherca commented Jul 8, 2013

恩, 这个是个好方法。
另外在View等不支持defaults的地方, 我override 了他的constructor, 在里面this.ref = [];
var View = Backbone.View.extend( {

  cls : 'DefaultView',

  //use to generate unique id
  idMark : '__tz_id__',

  //whether to show default page
  enableDefaultPage : false,

  //Default Page of current View
  defaultPage : null,

  constructor : function(){
    /*default extend method usees swallow copy only, 
     * which mean that all instance share the same reference type, 
     * it causes chaos
     * */
    this.children = [];
    return Backbone.View.apply(this, arguments);
  },

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment