Update: Problems solved, case closed.
I'm still having problems getting one part of my code to work.
My view now listens to the collection for updates, and what should happen is:
- ListView listens to Results Collection
- Results are synced
- ListView creates an ItemView for each Result
- ListView (ul) appends each ItemView (li)
Everything seems to work fine, up until the final step.
The function in ListView that is supposed to add the results to a list does not have access to the ListView's element.
I can create an ItemView, and retrieve it's element "<li>
", but the ListView's "<ul>
" cannot be referred to within the function.
Sample code bits from ListView:
el: $('.result-list'),
initialize: function() {
this.listenTo(this.collection, 'add', this.addOne);
},
addOne: function(result) {
view = new ItemView({ model: result });
this.$el.append(view.render().el);
},
In the above code, the variable view exists, as does it's element, but "this" doesn't refer to the ListView anymore.
Problem below solved
What I'm trying to accomplish is having a View module (search) able to trigger an event in a Collection (results).
When the Search View is submitted, it should pass the input field to the Collection's fetch method to retrieve results from the server. Currently, I can trigger a function from the View, but the function does not have access to any of the Collection's methods.
Previously, I had the View/Collection refer to each other directly by their variable names.
Since I have separated the code into modules, the View/Collection cannot access each other directly anymore.
Here is some of the code: (written in Coffeescript)
app.coffee - global_dispatcher is applied to Backbone
define [
'jquery'
'underscore'
'backbone'
'cs!router'
], ($, _, Backbone, Router) ->
# global_dispatcher added to all Backbone Collection, Model, View and Router classes
dispatcher = _.extend {}, Backbone.Events, cid: 'dispatcher'
_.each [ Backbone.Collection::, Backbone.Model::, Backbone.View::, Backbone.Router:: ], (proto) ->
_.extend proto, global_dispatcher: dispatcher
new Router()
router.coffee - This is where I'm having trouble. The function for 'getResults' is triggered, but the collection 'results' is not accessible from here.
define [
'backbone'
'cs!views/resuls/list'
'cs!views/results/search'
'cs!collections/results'
], (Backbone, ListView, SearchView, Results) ->
Backbone.Router.extend
routes:
# URL routes
'': 'index'
index: ->
results = new Results
new ListView { model: results }
new SearchView
@global_dispatcher.bind 'getResults', (data) ->
console.log results
search.coffee - View which triggers the event, it will successfully trigger the event and pass the correct arguments.
define [
'jquery'
'backbone'
], ($, Backbone) ->
Backbone.View.extend
events:
'submit #search-form': 'submit'
submit: (evt) ->
evt.preventDefault()
phrase = @.$('input').val()
@.$('input').val('')
args = name: phrase
@global_dispatcher.trigger 'getResults', args