添加到主干集合以响应事件

时间:2016-08-25 03:05:19

标签: backbone.js

我开始使用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读入骨干应用程序。

1 个答案:

答案 0 :(得分:1)

在初始化功能中,添加var myCollection = this.collection;并在myCollection

中使用MyPubSub.on(....