0

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
Matthew Lucas
  • 443
  • 1
  • 5
  • 15
  • Something I forgot to mention. I'm looking to make the code accomplish the behavior that I need (view triggers collection.fetch), but not necessarily in the way that is outlined above. If there is a better way than this, I would prefer to change whatever is necessary so that I can be doing it correctly. – Matthew Lucas Dec 28 '12 at 22:12
  • What are you trying to solve with this `@global_dispatcher` stuff? I ask because I've been coding Backbone apps for over a year now and have never had need for anything like that (and it seems like the easiest solution to your issue would be to solve whatever core problem you have without the global dispatcher, and get rid of it entirely). – machineghost Dec 29 '12 at 00:24
  • I want the search view to be able to make the collections fetch results from the server. My problem is doing this, while the models, collections, and views are split into modules. – Matthew Lucas Dec 29 '12 at 00:31

1 Answers1

0

If I'm understanding your problem correctly it's not hard to solve. Here's some dummy code to illustrate:

var Results = Backbone.Collection.extend();
var Search = Backbone.View.extend({
    someEventHandler: function() {
        // The next line accesses the collection from the view
        this.collection.fetch();
    }
});
var results = new Results();
var search = new Search({collection: results});

If you want your view to do something after the results come back, just bind an event handler on the collection:

var Search = Backbone.View.extend({
    fetchResposne: function() { /* do something*/},
    someEventHandler: function() {
        // The next line accesses the collection from the view
        this.collection.on('sync', this.fetchResponse);
        this.collection.fetch();
    }
});
machineghost
  • 33,529
  • 30
  • 159
  • 234
  • Wow, I was making this problem way more complicated than it needed to be. Thank you! I was converting my code to Require.js and trying to organize everything into separate modules. Once everything was separated, I got confused with how to make it all work again. Didn't even think about passing the collection to the view, and now I'm smacking my forehead. – Matthew Lucas Dec 29 '12 at 01:02
  • Thank you for answering my question! Your solution solved the problem I was having getting the View and Collection to work together. One part of my code still isn't working though, do you think you can take a look at the edit I made? – Matthew Lucas Dec 29 '12 at 02:01
  • You're quite welcome, but a quick point of Stack Overflow etiquette: you should always limit SO posts/questions to a single (as specific as possible) question. In other words "overloading" a question with multiple questions is a no no; you're better off just creating a new question. That being said I'm taking off and won't be around to answer the new question if you ask it, so the short answer is: you need to understand how `this` works in Javascript better. The even shorter answer is that if you add this code to your view's initialize, it should fix things: `_(this).bindAll('addOne');`. – machineghost Dec 29 '12 at 02:18
  • P.S. Read Underscore's documentation to understand why bindAll fixes things. If it doesn't fix things then I misunderstood your (new) problem, and in that case your best bet really is to start a new (Stack Overflow) question. – machineghost Dec 29 '12 at 02:21
  • Thank you again, and thanks for the advice. I'll be sure to follow SO etiquette in future posts. I read underscore's documentation, and bindAll did fix the issue I was having. – Matthew Lucas Dec 29 '12 at 02:30