2013-10-04 2 views
7

네트워크 연결이 없을 때 localstorage에서 데이터를 가져 오기위한 콜렉션 및 모델의 fetch 메소드를 대체하려고합니다.백본에서 fetch 메소드를 덮어 쓰기

이것은이 여기

a.The 성공이나 에러 함수 2 문제에 직면하고 수집

fetch:function(){ 
    if(online){ 
     return Backbone.Collection.prototype.fetch.call(this) ; 
    }else{ 
    // return Backbone.Collection.fetch event - with data from localstorage 
    } 
} 

내부 함수를 페치는

this.collection.fetch({ 
    success: function(data){ ... }, 
    error: function(){ ... } 
}); 

B에 실행 된 것은 아니다. 연결이없는 경우 어떻게 성공에 액세스 할 수 있도록 데이터를 컬렉션에 설정합니까?

답변

3

를 선호로 내가 문제 A에 대한 답을 발견했다, 그래서 $ 아약스는 약속을 반환 .

fetch:function(options){ 
    if(navigator.onLine){ 
     return Backbone.Collection.prototype.fetch.apply(this, options) ; 
    }else{ 
    return //Trying to findout 
    } 
} 

방법) (우리가

4

다음과 같이 시도해보십시오. 다음

fetch:function(){ 
    var dfd = new jQuery.Deferred(); 
    if(this.online){ 
     return Backbone.Collection.prototype.fetch.call(this) ; 
    }else{ 
    // Do your logic for localstorage here 
    dfd.resolve(); 
    } 

    return dfd.promise(); 
} 

그런 다음 사용할 수 있습니다 위의 예제를 할 수 있어야 또는 내가 조사한 후

this.collection.fetch().then(function() { 
    console.log('Successfully fetched from localstorage or server.'); 
}); 
1

그것은 백본의 동기화를 대체 할 가장 적합 할 수 있습니다 호출하는 함수에서 성공 기능에 액세스 할 수 fetch.apply하는 기능과 인수를 가져 옵션 인수를 통과 한 후 저축 및 편집까지 다루고 있습니다.

Backbone.sync = function(method, model, options, error) { 
    if(navigator.onLine){ // Or, however you determine online-ness 
     return Backbone.ajaxSync.apply(this, [method, model, options, error]); 
    } 
    return Backbone.localSync.apply(this, [method, model, options, error]);   
} 

나는이 밖으로 시도하지 않았다, 그러나 희망 당신은 아이디어를 얻을 : 당신이 backbone.localStorage.js에서 제공하는 로컬 저장소를 사용하는 경우, 재정의 (override)은 다음과 같이 보일 수 있습니다. 모델과 컬렉션에서 localStorage 속성을 정의하는 것을 잊지 마십시오.