Skip to content
This repository

Model Validation When Views use a Collection vs. a Model #18

Closed
wsgavin opened this Issue · 7 comments

2 participants

Warren Gavin Thomas Pedersen
Warren Gavin

I often create a view with a collection vs. a model when I want to add a new model to the collection. Using the collection.create() method works well, easy, etc. I feel like it gets messy when you try to create a view w/a model then add it to the collection as you need to reference both.

var view = new View({
    collection: myCollection,
    id: 'my-view'
});

Later on when I want to create the model I just use this:

this.collection.create({
    attr1: value,
    attr2: value
});

The normal backbone validation methods would kickoff on the save but of course I want to use backbone.validation. My issue is that backbone.validation looks for the view's model and does not consider a view's collection. I apologize if I've missed something in the documentation (or don't understand something about backbone itself) but it didn't jump out at me. Thoughts?

Thomas Pedersen
Owner

Hi, and thanks for your interest in the project!

It doesn't jump out because unfortunately it is not supported yet. It is on my todo list though.

Should not be too much work to get this in; if the view has a collection, I need to listen to the add and remove events on the collection and do the appropriate binding/unbinding on the model added/removed.

Hopefully I'll get around to add this in not too long. Hope you can wait a couple of days:)

Warren Gavin

Thanks for the reply and can of course wait (plenty of other stuff todo...).

Warren Gavin wsgavin reopened this
Warren Gavin

Sorry. I reopened cause I'm a goof and closed the issue.

Warren Gavin

Thanks for the addition.

Not sure if this complicates the scenario but I often pass both a model and collection to a view. I have not looked into the code enough but I've noticed some strange behavior (of course could just be me).

What’s happening is that the model in the current view does get validated. On the other hand the view that get the added class 'invalid' and data-error attribute is the last view generated from the collection.

I think what’s likely happening is that the collection get’s “bound” “n” number of times because I include the collection for each model I want to “view”.

Does that make sense?

Warren Gavin

Maybe (0.5.2) lines ~200-201 could do an 'if/else if' and default to model first. I guess you could also configure the behavior as well. I modified the code w/the 'if/else if' and all seemed to be working. Prob not the best option but worked ;).

Thomas Pedersen thedersen reopened this
Thomas Pedersen
Owner

Can you post an example of what you are doing? On jsfiddle.net maybe?

Thomas Pedersen
Owner

Not able to reproduce.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.