Skip to content

Commit 87989ee

Browse files
committed
added option to silence get() warnings for nested objects
1 parent 84aab41 commit 87989ee

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,15 @@ user.remove('addresses[0]');
144144
user.get('addresses').length; //=> 1
145145
```
146146

147+
## Warnings
148+
149+
Accessing a nested attribute will throw a warning in your console, because it's safer to use the getter syntax above. To silence these warnings, add an argument of `{silent: true}` to `get()`:
150+
151+
```javascript
152+
user.get('addresses[0]'); // gives a warning in your console
153+
user.get('addresses[0]', {silent:true}); // (silent)
154+
```
155+
147156
## Contributing
148157

149158
Pull requests are more than welcome - please add tests, which can be run by opening test/index.html.

backbone-nested.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ Backbone.NestedModel = Backbone.Model.extend({
1212
Backbone.Model.prototype.constructor.apply( this, arguments );
1313
},
1414

15-
get: function(attrStrOrPath){
15+
get: function(attrStrOrPath, opts){
16+
opts || (opts = {});
17+
1618
var attrPath = Backbone.NestedModel.attrPath(attrStrOrPath),
1719
childAttr = attrPath[0],
1820
result = Backbone.Model.prototype.get.call(this, childAttr);
@@ -28,7 +30,7 @@ Backbone.NestedModel = Backbone.Model.extend({
2830
}
2931

3032
// check if the result is an Object, Array, etc.
31-
if (_.isObject(result) && window.console){
33+
if (!opts.silent && _.isObject(result) && window.console){
3234
window.console.log("Backbone-Nested syntax is preferred for accesing values of attribute '" + attrStrOrPath + "'.");
3335
}
3436
// else it's a leaf
@@ -38,7 +40,7 @@ Backbone.NestedModel = Backbone.Model.extend({
3840

3941
has: function(attr){
4042
// for some reason this is not how Backbone.Model is implemented - it accesses the attributes object directly
41-
var result = this.get(attr);
43+
var result = this.get(attr, {silent: true});
4244
return !(result === null || _.isUndefined(result));
4345
},
4446

@@ -70,7 +72,7 @@ Backbone.NestedModel = Backbone.Model.extend({
7072
var attrPath = Backbone.NestedModel.attrPath(attrStr);
7173
if (_.isNumber(_.last(attrPath))){
7274
var aryPath = _.initial(attrPath),
73-
childAry = this.get(aryPath);
75+
childAry = this.get(aryPath, {silent: true});
7476

7577
// compact the array (remove falsy values)
7678
for (var i = 0; i < childAry.length; i++){

0 commit comments

Comments
 (0)