Alive Developer
Alive Developer

Reputation: 1022

ember.js: combine search and filter

Having this controller:

App.ProductsController = Ember.ArrayController.extend Ember.PaginationMixin,
  sortProperties: ["number"]

I would like to add the "search" functionality, in this (working) way

App.ProductsController = Ember.ArrayController.extend Ember.PaginationMixin,
  sortProperties: ["number"]
  search: ''
  filteredContent: (->
    search = @get("search")
    @get("content").filter (item)->
      name = item.get("name").toLowerCase()
      name.match(search.toLowerCase())
  ).property("submittedSearch")

  filterContent: ->
    @set "submittedSearch", @get("search")

The problem is that when I apply my search i'm losing my sorting defined before. What could I do?

Upvotes: 0

Views: 690

Answers (1)

Mudassir Ali
Mudassir Ali

Reputation: 8041

From the official documentation

Ember.SortableMixin provides a standard interface for array proxies to specify a sort order and maintain this sorting when objects are added, removed, or updated without changing the implicit order of their underlying content array:

Ember.SortableMixin only cares about the content array while we do get, here you're trying to do get on filteredContent which the mixin doesn;t care !

So what I'd suggest you is make the content as computed property which depends on selected search as follows,

App.ProductsController = Ember.ArrayController.extend Ember.PaginationMixin,
  sortProperties: ["number"]
  search: ''
  content: (->
    search = @get("search")
    @get('products').filter (item) ->
      name = item.get("name").toLowerCase()
      name.match(search.toLowerCase())
  ).property('submittedSearch')

Inside the route setupController set the main list to products property of controller instead of content

App.ProductsRoute = Ember.Route.extend
  setupControllers: (controller, model) ->
    controller.set('products'), App.Products.find()

Now, your content would be filtered courtesy ComputedProperty, sorted courtesy the "mixin"

Upvotes: 1

Related Questions