I theme of the code is that i have an application where the user enters a search string and on submit, the application redirect to another application(created using emberjs). Here, we have a dropdown created using bootstrap and a search box( $('#query') ). The search box needs to be populated with the search string and the dropdown needs to be set to some option.
The didInsertElement is a callback provided by emberjs and searchStringChanged is an observer that observes the searchString(in the url) and repopulates the searchbox with the updated searchString.
My current controller code is as:
App.PortfoliosIndexController = Ember.ArrayController.extend(
queryParams: ['search_string']
search_string: null
filteredPortfolios: (->
search_string = @get("search_string")
results = @get('content')
if search_string
results = results.filter((portfolio) ->
portfolio.get('portfolio_name').toLowerCase().indexOf(search_string.toLowerCase()) > -1
)
results
).property('content', 'search_string')
)
My current ember view code is as:
App.PortfoliosListView = Ember.View.extend(Ember.PaginationMixin,
templateName: 'portfolios/list'
itemsPerPage: 5
modifySelectBox: ->
$('#query').val @searchString
$(".dropdown-menu ul li").removeClass "selected"
$(".dropdown-menu ul li:nth-child(2)").addClass "selected"
$(".filter-option").text $(".dropdown-menu ul li.selected a span").text()
$("#category").get(0).selectedIndex = 1
searchStringChanged: (->
###
$('#query').val @searchString
$(".dropdown-menu ul li").removeClass "selected"
$(".dropdown-menu ul li:nth-child(2)").addClass "selected"
$(".filter-option").text $(".dropdown-menu ul li.selected a span").text()
$("#category").get(0).selectedIndex = 1
###
modifySelectBox()
).observes 'searchString'
didInsertElement: ->
###
$('#query').val @searchString
$(".dropdown-menu ul li").removeClass "selected"
$(".dropdown-menu ul li:nth-child(2)").addClass "selected"
$(".filter-option").text $(".dropdown-menu ul li.selected a span").text()
$("#category").get(0).selectedIndex = 1
###
modifySelectBox()
)
I removed the duplicate code and moved it to an modifySelectBox method which i intended to call from callback and observer but the modification doesnt work. How can remove the duplication?
didInsertElementfires after the parent element of the view is rendered in the DOM. If that view contains other elements, they may not be rendered until afterdidInsertElementis called. Look at mavilein.github.io/javascript/2013/08/01/… for details. - Josh Padnick.val(). Using jQuery in this way can sometimes expose you to race conditions. You might consider using query_params (emberjs.com/guides/routing/query-params) to populate your search box instead. - Josh Padnick