2014-07-18 2 views
0

사용 backbone.js 내 서버에서 모델을 가져 와서이를 기반으로 밑줄 템플릿을 렌더링하려고합니다. 먼저 다음 호출 함수를 사용하여 API 호출 결과를 사용하지 않고 시도했습니다.myModel.fetch()가 완료되면 백본 템플릿을 렌더링 하시겠습니까?

render: function(options) { 
    this.ticketId = options.ticketId; 
    var that = this; 
    var ticketModel = new TicketModel({'id': that.ticketId}); 
    $.when(ticketModel.fetch()).done(function(){ 
     console.log(ticketModel); // this outputs the correct model 
    }); 
    var template = _.template($('#tab-content-template').html(), {ticketId: that.ticketId}); 
    this.$el.html(template); 
}, 

이것은 완벽하게 작동합니다.

render: function(options) { 
    this.ticketId = options.ticketId; 
    var that = this; 
    var ticketModel = new TicketModel({'id': this.ticketId}); 
    $.when(ticketModel.fetch()).done(function(){ 
     console.log(ticketModel); 
     console.log($('#tab-content-template').html()); 
     var template = _.template($('#tab-content-template').html(), {ticketId: that.ticketId}); 
     this.$el.html(template); 
    }); 
}, 

하지만 불행히도,이 이상한 것은 그것이 콘솔에서 HTML을 출력한다는 것입니다

Uncaugt TypeError: Cannot read property 'html' of undefined.

라는 오류가 발생합니다 그래서 템플릿을 렌더링하는 API를 호출의 결과를 사용하여 시도 console.log($('#tab-content-template').html());에서 올바르게 발생합니다. 내가 얻는 오류는 읽는 줄에 있습니다. this.$el.html(template);

어떻게 처음으로 html()을 얻을 수 있고 그 후에 html 속성을 찾을 수 없다고 할 수 있습니까? 나는 여기에 완전히 붙어있어 .. :

모든 팁을 환영합니다!

+0

여기에서 새로운 것을 배웠습니다. 가져 오기가 $를 (를) 반환했습니다.지연 객체, 건배 – Quince

답변

0

귀하의 문제는 더 이상 귀하가 생각하는 바를 언급하지 않습니다. 코드에 넣었습니다

var that = this; 

이것은 클로저가 실행될 때 "this"의 컨텍스트를 유지할 수 있도록하는 공통 패턴/트릭입니다. 클로저 안에 "그"는 "this"가 참조해야한다고 생각하는 것을 참조 할 것입니다. 이

를 실행하는

$.when(ticketModel.fetch()).done(function(){ 
     console.log(ticketModel); 
     console.log($('#tab-content-template').html()); 
     var template = _.template($('#tab-content-template').html(), {ticketId: that.ticketId}); 
     that.$el.html(template); 
    }); 

내가 usally 함수가 실행될 때 컨텍스트 확신 할 수 있도록 jQuery의 프록시 기능의 사용을 "이"을 "있음"변화

시도

$.when(ticketModel.fetch()).done($.proxy(function(){ 
     console.log(ticketModel); 
     console.log($('#tab-content-template').html()); 
     var template = _.template($('#tab-content-template').html(), {ticketId: that.ticketId}); 
     this.$el.html(template); 
    },this)); 

왜 $ ('# tab-content-template')가 html()인지에 대한 또 다른 질문이 있습니다. JQuery를 전역 네임 스페이스에 직접 사용하고 있기 때문에 액세스가 가능하기 때문에 $ el 보기의 속성이므로보기에 액세스 할 수 없으면 액세스 할 수 없습니다. 그 재산.

+0

@ kramer65이 문제가 해결 되었습니까? – Quince

0

http://backbonejs.org/#Model-fetch보기 - options 인수가 successerror 콜백 받아 들인다 : 당신은 당신이에 밑줄/소호 - 대시 _.bind() 기능을 사용할 수 있습니다이 콜백에서 현재의 뷰 객체의 컨텍스트를 사용해야 할 경우도

ticketModel.fetch({ 
    success: function(model, response, options) { 
     // render the template 
    } 
}); 

을 컨텍스트 전달 :

ticketModel.fetch({ 
    success: _.bind(function(model, response, options) { 
     // Render the template using some method of the view: 
     this.renderMyTemplate(model); 
    }, this) 
}); 

를하거나 자체 전달 방법 :

0

여기에 $가 없어도 백본이 가져 오기 호출에 대한 약속을 반환합니다. 아래 코드는 당신을 위해 작동합니다. 또한 렌더링 함수 밖에서 템플릿을 컴파일하는 것을 고려하십시오. 템플릿을 컴파일하는 것은 약간 무거운 작업이므로 완료되면 캐싱해야합니다.

var _this = this; 
ticketModel.fetch().done(function() { 
    var template = _.template($('#tab-content-template').html(), {ticketId: that.ticketId}); 
    _this.$el.html(template); 
}); 
관련 문제