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
을var myCollection = this.collection;
를 추가하고 사용! 왜 그런 생각을하지 않았는가 .. – rw950431또는'initialize()'내부에'var self = this', 그리고 콜백 내부에'self.collection.add (evt.data)'가 있습니다. –