Mefhisto1
Mefhisto1

Reputation: 2228

Iterating over a Backbone model's attributes and passing them to a function

I want to validate my model attributes by explicitly calling a validate function. I'm not sure how to do that exactly,

collection.forEach(function (model) {
                model.forEach(function(attribute) {
                    someFunction(attribute);
                })
            });

this is the behavior I'd like to achieve somehow

Upvotes: 0

Views: 1399

Answers (2)

nikoshr
nikoshr

Reputation: 33344

You can use collection.each to iterate over the models and _.each on the keys of the model to apply your function:

collection.each(function(model) {
    _.each(model.keys(), function(attribute) {
        console.log(attribute, model.get(attribute));
    });
});

And a demo http://jsfiddle.net/6YP9W/

Or work directly with the attributes hash if you prefer

collection.each(function(model) {
    _.each(model.attributes, function(val, attribute) {
        console.log(attribute, val);
    });
});

http://jsfiddle.net/6YP9W/1/

Upvotes: 3

Geert Wille
Geert Wille

Reputation: 1654

You better use the backbone manner described in this post... Excellent guide :)

Upvotes: 0

Related Questions