简体   繁体   中英

Backbone - iterating over objects in an array attribute

I have a model with two arrays, bright and normal. Each array includes objects which are representing colors. I want to implement in model a method allowing to set some properties (for example hue) of this colors. So I wrote this:

setHue: function(hue) {
    _.each([this.get('brigth'), this.get('normal')], function(colors) {
        _.each(colors, function(color) {
            color.setHue(hue + this.getHue());
        });
    });
},

I think it's clear - I try to iterate over every color in both bright and normal arrays. And it doesn't update colors inside these arrays. This color inside _.each seems to have a new value, but it looks it's only a copy of color, not a reference. Do anyone know how to do what I want? I mean with _.each loop, I don't wanna mess up with for , length and indexes.

Bright is misspelled. You entered brigth.

Hm, I think you have a general problem here. Let's try with an example:

this.get('brigth')

will return an array, not a model, correct?

If so,

_.each([this.get('brigth'), this.get('normal')], function(colors) { ...

will loop over an array of arrays, ie colors will get an array, not a model nor a collection. Consequently, color will be a item of an array (I assume a string). Thus color with not have a method setHue.

Additionally, Paul is right as well this.getHue() this does not refer to a model, since you are switching context twice (once for each each-Loop). I hope I did not get it totally wrong here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM