Question

i'm starting with Backbone and i'm writing an application for cellphones sales. But my doubt is about the javascript execution flow specifically.

The situacion is that i have a custom method to deny duplicates on my cart collection, these method is something like this:

var Cart = Backbone.Collection.extend({
            contains : function(aProduct){
                _.each(this.models, function( element, index, list ){
                    if( element.get('product').get('id') == aProduct.get('id') ){ 
                        return true; 
                    }
                });
                return false;
            }
        });

The method detects the duplicates and try to return true, but that line isn't the last one, because the last statement executed was the "return false". At this point i realize that i have a misunderstanding in this javascript execution flow.

maybe one of you can enlight me with your knowledge

thanks

Was it helpful?

Solution

You are returning true from the function you passed into _.each. That is different from your contains function. Here is a way to get it working:

var Cart = Backbone.Collection.extend({
            contains : function(aProduct){
                var doesContain = false;
                _.each(this.models, function( element, index, list ){
                    if( element.get('product').get('id') == aProduct.get('id') ){ 
                        doesContain = true; 
                    }
                });
                return doesContain;
            }
        });

However, an even better way (assuming that is lodash or underscore), would be to use _.any

var Cart = Backbone.Collection.extend({
            contains : function(aProduct){
                return _.any(this.models, function( element ){
                    if( element.get('product').get('id') == aProduct.get('id') ){ 
                        return true; 
                    }
                });
            }
        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top