gmac / backbone.epoxy

Declarative data binding and computed models for Backbone
http://epoxyjs.org
MIT License
615 stars 89 forks source link

Bind to a subset of a collection #69

Closed Prinzhorn closed 9 years ago

Prinzhorn commented 10 years ago

I currently have the need to use something like these (which all have two things in common: they're inactive and solve the same issue)

Since epoxy already has all this dependency tracking built in, do you think it would be a good idea to integrate something like this into epoxy?

Example:

var TodosCollection = Backbone.Collection.extend({
    model: TodoItemModel,
    view: TodoItemView
});

var collection = new TodosCollection();
var completedCollection = collection.project({only: 'completed'});

Now completedCollection would behave exactly like a normal collection (fires the correct events etc.). It is readonly though, because it's just a filtered view of the other collection (note: it doesn't need to be readonly. Some of the projects above allow two way sync). And instead of completed we could use any property or computed of the TodoItemModel.

chiplay commented 10 years ago

@Prinzhorn check out https://github.com/jmorrell/backbone.obscura - we've been really happy with it for proxied collections.

Prinzhorn commented 10 years ago

@chiplay thanks, I haven't tried this one yet I guess. Are you using it together with Epoxy and collection binding?

Prinzhorn commented 10 years ago

I went ahead and implement this as a handler. Pretty straight forward actually. This also solves #3

https://gist.github.com/Prinzhorn/8080ec50934fbcb369f7

I wasn't interested in sorting or paginating anyway, I just wanted to filter elements but the toggle binding doesn't work for this case.

Edit: Just found that it doesn't work on initial rendering since it happens before Epoxy adds the element to the DOM. I'll see what I can do. I was using it to hide elements in a list as the user searches, where this case naturally didn't occur.

Prinzhorn commented 10 years ago

Reopening, maybe @gmac has an idea on how to solve the initial-render issue.

gmac commented 9 years ago

RE: original ticket discussion about filtering collections... +1 on https://github.com/jmorrell/backbone.obscura. That looks great (I may have to start using that on some projects).

RE: initial render issue for your "if" binding... When in doubt, make it async. Epoxy bindings allow you to define an init method (see https://github.com/gmac/backbone.epoxy/blob/master/backbone.epoxy.js#L613-L618), within which you should be able to define a setTimeout(..., 0) to schedule an initial rendering on the next event loop.