응용 프로그램의 주요 기능을 다시 디자인하는 동안 백본을 처음 사용하고 있습니다. 목표는 동일한 백본 컬렉션 /보기 코드를 사용하여 동일한 페이지에서 여러 다른 목록을 관리하는 것입니다. 기능은 모두 동일하며 변경되는 데이터 일뿐입니다.잘못된 인스턴스에서 Backbone.js 이벤트가 발생했습니다.
지금까지 성공했지만 알아 내지 못하는 문제를 발견했습니다. 양식 입력에서 새 항목을 추가하면보기가이를 처리하고 ajax로 저장하는 콜렉션의 add 함수를 호출합니다. 완료되면 콜렉션은 뷰를 다시 렌더링하도록 트리거하는 "additem"이벤트를 호출합니다.
그러나 최근에로드 된 뷰의 이벤트 만 호출되는 경우가 발생합니다. 이벤트 이름을 전적으로 변경하여 접두사가 붙어서 각보기마다 고유해야하므로 - 당황 스럽습니다.
많은 코드가 제거되었지만 문제의 원인은 아래에 있습니다. 이 코드 예제에서는 필자가 필요로하는 각 목록 유형의 이벤트에 접두사를 붙이려고했지만 잘못된보기에서 이벤트를 호출하는 것과 관계가 없습니다.
// A collection is made to manage the data - saves to the server, loads, updates, etc
var ListItems = Backbone.Collection.extend({
initialize: function(models, options) {
this.url = options.url;
this.options = options;
},
/**
* We'll use a custom addItem handler so that we're not triggering
* events or ajax requests on .add(), since .fetch() uses it
*/
addItem: function(obj,ajax_elem){
self_col = this;
$.ajax({
type: 'POST',
url: this.options.add_url,
data: obj,
success: function(resp){
if(resp.success === true){
console.log('collection calls ep ' + self_col.options.ep+':addItem');
Backbone.Collection.prototype.add.call(self_col, {text:obj.text,id:resp.id});
self_col.trigger(self_col.options.ep+':addItem');
} else {
self_col.trigger(self_col.options.ep+':error', resp.errors);
}
// ... rest of stuff
// View manages rendering the items to the page, etc
ListView = Backbone.View.extend({
initialize: function(){
self = this;
this.ep = self.$el.attr('id');
this.collection.bind(this.ep+":addItem",function(){
console.log('view thinks ep is: ' + self.ep+":addItem");
console.log(self.$el);
self.render();
$(window).trigger('Snowy:ajax:stop', self.$el.find(':submit'));
});
// Load the category list
categoryList = new ListView({
collection: new ListItems(INIT_CATEGORIES, {
ep: 'categories',
// other opts
}),
el: $("#categories")
});
['window.self' (https://developer.mozilla.org/en-US/docs으로
똑같이 /DOM/window.self)는'self = this'를 하나 더 불쾌하게 만듭니다. –