2016-08-25 40 views
0

我開始使用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蒸汽讀入骨幹應用程序。

回答

1

在初始化函數,內MyPubSub.on(....

+0

當然添加var myCollection = this.collection;,並使用myCollection!爲什麼我沒有想到...... – rw950431

+0

或者,在'initialize()'裏面'var self = this',然後在回調裏面'self.collection.add(evt.data)'。 –