添加到 backbone 集合以响应事件

Add to backbone collection in response to event

我刚开始使用 backbone.js 但在这一点上卡住了:我想从 websocket 获取数据并将其添加到集合中。

我从 http://adrianmejia.com/blog/2012/09/11/backbone-dot-js-for-absolute-beginners-getting-started/ 中的代码开始,但是当我尝试添加事件处理时,我不知道如何从事件中访问集合。

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);

我在这方面完全是个新手,所以我怀疑我在范围界定方面犯了一些基本错误。还可以使用其他方法将 websocket steam 读入 backbone 应用程序。

在初始化函数中,添加var myCollection = this.collection;并在MyPubSub.on(....

中使用myCollection