rw950431
rw950431

Reputation: 115

Add to backbone collection in response to event

I'm getting started with backbone.js but have got stuck at this point: I want to get data from a websocket and add it to a collection.

I've started with the code from http://adrianmejia.com/blog/2012/09/11/backbone-dot-js-for-absolute-beginners-getting-started/ but when I try to add in the event handling I cant figure out how to access the collection from within the event.

var AppView = Backbone.View.extend({
      // el - stands for element. Every view has a element associate in with HTML content will be rendered.
      el: '#container',
      template: _.template("<h3>Hello <%= who %></h3>"),
      // It's the first function called when this view it's instantiated.
      initialize: function(){
        console.log(this.collection) //<-- this.collection is OK here
        MyPubSub.on('message', function (evt) {
          this.collection.add(evt.data) //<-- TypeError: this.collection is undefined
        });

        this.render();
      },
      // $el - it's a cached jQuery object (el), in which you can use jQuery functions to push content. Like the Hello World in this case.
      render: function(){
        this.$el.html(this.template({who: 'planet!'}));
      }
    });

   function init()
   {
        var websocket = new WebSocket("ws://example.com:8088");
        MyPubSub = $.extend({}, Backbone.Events);
        websocket.onmessage = function(evt) {
          console.log("message")
          MyPubSub.trigger('message',evt)
        };
        var appView = new AppView({collection:new AlertCollection()});
   }
  window.addEventListener("load", init, false);

I'm a complete newbie at this so I suspect I've made some kind of basic error in scoping. Also open to other approaches to read a websocket steam into a backbone app.

Upvotes: 0

Views: 45

Answers (1)

bvoleti
bvoleti

Reputation: 2552

In the initialize function, add var myCollection = this.collection; and use myCollection within the MyPubSub.on(....

Upvotes: 1

Related Questions