Last active
December 19, 2015 11:09
-
-
Save freizl/5945696 to your computer and use it in GitHub Desktop.
Two practices to extend Backbone model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 !!! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
恩, 这个是个好方法。
另外在View等不支持defaults的地方, 我override 了他的constructor, 在里面this.ref = [];
var View = Backbone.View.extend( {