backbone.validation icon indicating copy to clipboard operation
backbone.validation copied to clipboard

Can you bind multiple views to the same model?

Open SnidelyWhiplash opened this issue 11 years ago • 4 comments

I'm using Marionette, but it shouldn't make a difference as far as this question.

I have two views, a LoginView and a SignupView (both forms). They are shown at the same time, and instantiated with an empty User model, eg:

onRender: function () {
  var user = new User();
  this.login.show(new LoginView({model: user}));
  this.signup.show(new SignupView({model: user}));
}

each of those views is doing

initialize: function () {
  Backbone.Validation.bind(this);
}

but only the SignupView is seeing the validation effects. Is there a way to have the model validation affect both views, or am I going to have to send them each a separate Model instance?

Thanks for the awesome plugin!

SnidelyWhiplash avatar May 27 '14 06:05 SnidelyWhiplash

I have done this in the past. Don't bind directly to the view but use the mixin on the model instead.

SomethingSexy avatar Jul 06 '14 18:07 SomethingSexy

Thanks for the reply. So then you just listen for the vaildated:* events on the model within the view directly..?

SnidelyWhiplash avatar Jul 12 '14 06:07 SnidelyWhiplash

Yep, you can just have your view listenTo the validated events on the model, then wire up your UI interactions that way. We ended up need something a little bit more robust so we actual manually call the preValidation method on the model for what we are trying to validate (because we are doing real-time validation) and then we do whatever we need based on valid/invalid.

I might also suggest making some sort of view mixin so that you can mixin in that with any view you need to handle model validation.

SomethingSexy avatar Jul 12 '14 20:07 SomethingSexy

Sounds good, thanks for the rundown. For clarification on one point, I thought preValidate() didn't fire the events..? Does it even set _isValid on the model..? Going off memory for now, I can dive into the code to determine. Thanks!

SnidelyWhiplash avatar Jul 12 '14 21:07 SnidelyWhiplash