2
\$\begingroup\$

I have a Backbone.Collection which has some models in it. Each model has a boolean property called 'special.' Only one model should be special at any given time.

I've got the following to enforce this, but I'm wondering if it could be clearer or if there is a more appropriate way to enforce such behavior:

//  Ensure that only 1 model is ever special.
this.on('change:special', function (changedModel, special) {

    if (special) {
        this.each(function (model) {
            if (model !== changedModel) {
                model.set('special', false);
            }
        });
    }

});

I don't like this because it seems overly verbose and also gives a period of time where two items are special.

\$\endgroup\$
1
\$\begingroup\$

That seems wrong on a few levels.

  • Slows down every update call
  • This is pretty much 'magic happens here'
  • I feel this should be enforced in the UI, is it not too late for this in Backbone?

I would modify the setter to accomplish what you need : https://stackoverflow.com/a/9415926/7602

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.