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の蒸気をバックボーンアプリに読み込むための他の方法もあります。初期化関数で
内
myCollection
を使用!なぜ、私はそれを考えていませんでしたか? – rw950431あるいは、 'initialize()'の中に 'var self = this'を入れ、コールバックの中に' self.collection.add(evt.data) 'を入れてください。 –