1

나는 언제 어디에서 컬렉션을 인스턴스화하고 백본 응용 프로그램에서 가져올 지에 대해 약간 의아해합니다.Backbone.js 언제 어디서 수집 데이터를 가져와야합니까?

지금까지 몇 가지 방법으로 작업 해 보았습니다. 매우 간단한 CRUD 연락처 관리자 앱에서 일하고있었습니다. Im은 어지럽 죠. 그러나 몇 가지 규칙과 'gotchas'가 있다고 확신합니다. 알지 못한다.

이것들은 제가 보았을 때나 작동 시키거나, 일종의 'work'옵션입니다 :) 옵션 4는 개념적으로 앞으로 나아갈 것 같습니다. 그러나 나는 그것을 어떻게 망쳐 놓고 있습니다.

나쁜 생각 : 1) 라우터로 무엇인가를하기 전에 새로운 컬렉션을 인스턴스화하고 fetch를 호출 한 다음 app 준비된 뷰를 doc 준비 문으로 시작합니다.

이 일
// Create an Instance of the collection 
    App.contacts = new App.Collections.Contacts; 

    App.contacts.fetch({update: true, remove: false}).then(function() { 
     new App.Views.App({ collection : App.contacts }); 
    }); 
  • -하지만 앱에서 여러 컬렉션을 가지고 있다면 그 정말 올바른 방법은 아닌 것 같아, 나는이 아이디어가 실패 생각합니다.

나쁜 생각 : 2) 내가 라우터를 사용하기 시작했을 때, 나는 라우터 초기화 방법에서도 위와 같은 효과가 있다고 생각했지만 같은 문제를 안고 있다고 생각합니다.

나쁜 생각 : 3) 나는 여러 가지 장소에서 읽는 것이 좋지 않은 콜렉션 init 메소드에서 가져 오는 것을 시도했다. 이것은 나쁜 생각이었다.

좋은 아이디어 (?) : 그러나 나는 할 수 없다. : 4) 나는이 뷰를 인스턴스화 할 때 콜렉션에 대한 데이터를 얻는 것이 합리적이라고 생각했다. 컬렉션 및 작업 컬렉션은 라우터에서 뷰를 인스턴스화 할 때마다 서버에서 가져온 것일뿐입니다. 이것은 나에게 승리 공식처럼 보입니다. 그러나 이것을 View 초기화 또는 렌더링 메소드에 넣으려고 할 때 내 this.collection.on('add', this.addOne, this);은 정의되지 않은 .on을 호출 할 수 없습니다. (NB : 성공 함수에 넣으려고했습니다.)

이게 내 머리를 쓰고있어.

건배.

EDIT : 추가 코드로 아래에서 설명 할 두 가지 부하를 진단 할 수 있습니다. 내 라우터에

var ViewManager = { 
    currentView : null, 
    showView : function(view) { 
     if (this.currentView !== null && this.currentView.cid != view.cid) { 
      this.currentView.remove(); 
     } 
     this.currentView = view; 
     return view; 
    } 
} 

: 내 라우터 파일에서

나는이 유틸리티 OBJ를 사용하고 난 내 길

list: function() { 
    console.log('backbone loading list route'); 

    var AllContactsView = new App.Views.Contacts({ //init method runs now 
     collection : App.contacts 
    }); 

    ViewManager.showView(AllContactsView); 

}, 

내 컬렉션에서이 메소드를 호출하고있어

App.Collections.Contacts = Backbone.Collection.extend({ 
    model: App.Models.Contact, 
    url: 'contacts', 
}); 

내보기

내 앱에서

JS

// Run App 
jQuery(document).ready(function($) { 

    // Create an Instance of the collection 
    App.contacts = new App.Collections.Contacts; 

    // Init BB Router 
    new App.Router.Route; 
    Backbone.history.start(); // Kick it all off. 

}); 
+0

위의 코드에서 컬렉션이 두 번 호출되는 이유를 볼 수 없습니다. 'App.Collections.Contacts' 코드를 추가 할 수 있습니까? –

+0

완료,하지만 그게 다라고 생각하지 않습니다. – pushplaybang

답변

0

Google 검색, 독서 및 테스트가 많은 후 나는 다음을 수행했습니다. 우리가 초기화 작업을 실행하도록 백본을 강요하고 있기 때문에 이것이 최적이라고 생각하지 않습니다. 이것은 기본 동작이 변경되었다는 사실을 무시한 것처럼 느껴지더라도 대부분의 예제 응용 프로그램에서 수행되는 방식 인 것 같습니다. 이유가 있었습니까?

궁극적으로 이것은 현재 작동하지만 나는 대안을보기 위해 매우 흥분됩니다.

list: function() { 
    console.log('backbone loading list route'); 

    var AllContactsView = new App.Views.Contacts({ //init method runs now 
     collection : App.contacts 
    }); 

    ViewManager.showView(AllContactsView); 

}, 

로 : 나는 목록 노선에이 전화를 내 라우터에서

var ViewManager = { 
    currentView : null, 
    showView : function(view) { 
     if (this.currentView !== null && this.currentView.cid != view.cid) { 
      this.currentView.remove(); 
     } 
     this.currentView = view; 
     return view.render(); 
    } 
} 

:

/*Collection view 
- - - - - - -*/ 
App.Views.Contacts = Backbone.View.extend({ 
    tagName: 'tbody', 
    initialize: function() { 
      this.listenTo(this.collection, 'add', this.addOne); 
      this.listenTo(this.collection, 'reset', this.addAll); 
      this.listenTo(this.collection, 'all', this.render); 
      this.collection.fetch({reset:true}); 
    }, 
    render: function() { 
     // append the list view to the DOM 
     $('#allcontacts').append(this.el); 
     return this; 
    }, 
    addAll : function() { 
     this.collection.each(this.addOne, this); 
    }, 
    addOne: function(model) { 
     var contactView = new App.Views.Contact({ model: model}); 
     this.$el.append(contactView.render().el); 
    } 
}); 

나는 다시 렌더링 호출을 추가 한이 유틸리티를 가지고 나는 사소한 문제가 있거나 2 가지가있을 수 있다고 느꼈지만, 현재는 내 앱에서 작동하며 나중에 다시 의심 할 여지없이 다시 돌아올 것입니다.

1

로보기는 다음과 같이해야합니다 :

App.Views.Contacts = Backbone.View.extend({ 
    tagName: 'tbody', 

    initialize: function() { 

     this.listenTo(this.collection, 'reset', this.render); 
     this.listenTo(this.collection, 'add', this.addOne); 

     vent.on('contactR:closeAll', this.closeView, this); 

     this.collection.fetch(); 
    }, 
}); 
+0

멋지다. 멋지다. 멋지다. 멋지다. 멋지다. 나는 콜렉션을 주입하면서 완전히 차가워 진다고 표현했지만, 그 이유는 언제 어디서 언제 가져올 지, 내 가정은 라우터에 의해 인스턴스화, - 생각? – pushplaybang

+0

새로운 답변으로 업데이트했습니다. –

+0

멋진 알았습니다. - 저의 아이디어에 대한 여러분의 피드백을 부탁드립니다. – pushplaybang

0

은 어디 때문에 그 성가신 작은 this 키워드 melarky의 내 오류를 Irealised, 이제 그 문체 나 개념 질문 아마

에서 라우터를 호출하기 전에 내 설정 파일. 뷰에서

list: function() { 
    var AllContactsView = new App.Views.Contacts({ 
     collection : App.contacts 
    }); 

    ViewManager.showView(AllContactsView); 

}, 

: 내 라우터에서

App.contacts = new App.Collections.Contacts; 

나에게

App.Views.Contacts = Backbone.View.extend({ 
    tagName: 'tbody', 

    initialize: function() { 
     var that = this; 
     this.collection.fetch({ update: true, remove: false}).then(function() { 
      that.collection.on('add', that.addOne, that); 
      vent.on('contactR:closeAll', that.closeView, that); 
      that.render(); 
     }); 


    }, 
}); 

이는 것보다 유연하고 개념적으로 바로 나에게,하지만이에 대한 피드백을 사랑 많은 대답.

+0

위의 @Ridas 솔루션이 더 깨끗하다고 ​​생각합니다. – pushplaybang

0

그래서 render 메소드의 .each가 가져 오기가 성공적으로 연결되고 sync 이벤트가 시작되기 전에 추가 이벤트가 발생하므로 무의미했습니다. 따라서 add 이벤트에 대한 listenTo는 필요할 때 addOne을 발생시키고 render 이벤트는 이제 컬렉션을 dom 동기화에 추가합니다.

App.Views.Contacts = Backbone.View.extend({ 
tagName: 'tbody', 

initialize: function() { 

     this.listenTo(this.collection, 'sync', this.render); 
     this.listenTo(this.collection, 'add', this.addOne); 

    this.collection.fetch(); 

}, 

render: function() { 
    // append the list view to the DOM 
    $('#allcontacts').append(this.el); 

    /* 
    render each of the single views - removing this seems to set everything 
    right in the world 
    */ 

    // this.collection.each(this.addOne, this); 
    return this; 
}, 

addOne: function(contact) { 
    var contactView = new App.Views.Contact({ model: contact}); 
    this.$el.append(contactView.render().el); 
} 

}); 
+0

이것을 제거하면 나중에 뷰를 다시 인스턴스화하려고 시도 할 때와 마찬가지로 실패합니다. 새 뷰를 추가하거나 편집 한 후에 뷰는 시각적으로 렌더링되지 않습니다. – pushplaybang