2014-03-01 2 views
0

jQuery 1.11과 함께 Backbone.js 1.1.2를 사용하고 있습니다.백본 이벤트를 사용할 수 없습니다.

나는 매우 간단하다고 생각합니다.

모델을 설정했습니다 : Contact 및 컬렉션 : ContactList. 내가보기 이니셜의 변화 이벤트에 바인딩 할 때

내가 성공 ContactList.fetch()

에서 얻은 모델 ContactView 뷰를 렌더링해야하지만 :

this.model.on('change', this.render, this); 

을 ... 내가 얻을 :

backbone Uncaught TypeError: Object #<Object> has no method 'on' 

그래서 문서로 돌아가서 .on()Backbone.Events의 일부이며, 어쨌든 나는 ㅇ이를 이용할 수 있도록 모델을 확장 (왜 모델의 아웃 - 오브 - 박스 기능 ??이 하지 부분이다) 나는

_.extend(this, Backbone.Events); 

선언하려고했습니다

... 바인딩을 선언하기 전에 ContactView의 초기화 함수 내부에는 주사위가 없습니다.

Backbone.Events 기능을 사용하려면 어떻게해야합니까?

갱신 : 모든 관련 코드 (산세 템플릿)

var Contact = Backbone.Model.extend({ 
    defaults: { 
     FirstName: '', 
     ...[etc] 
    }, 
    initialize: function() { 
    } 
}); 

var ContactList = Backbone.Collection.extend({ 
    model: Contact, 
    url: '/api/Contacts/getall' 
}); 

var ContactView = Backbone.View.extend({   
    initialize: function() { 
     this.render(); 
     this.model.on('change', this.render, this); 
    }, 
    render: function() { 
     var template = _.template($('#contact_template').html(), this.model); 
     this.$el.html(template); 
    } 
}); 

var contactList = new ContactList(); 

contactList.fetch({ 
    success: function (collection, response, options) { 
     contactList.models.forEach(function (m) { 
      var $el = $('<li />') 
       .addClass('adminItem clearfix') 
       .appendTo($('#contactList')); 
      new ContactView({ el: $el, model: m.attributes }); 
     }); 
    }   
}); 
+0

백본 모델 [이미 Backbone.Events는 혼합 한] (http://backbonejs.org/docs/backbone.html#section-36). 당신이 심문했듯이, 그들이하지 않으면 바보가 될 것입니다. 'this.model'은'Backbone.Model' 인스턴스입니까? – bejonbee

+0

@bejonbee : 그래서 다른 것이 틀림 없습니다. 더 많은 코드를 게시했습니다. – Faust

+1

'tagName : 'li', className : 'adminItem clear fix'를'ContactView'에 추가하는 것에 대해 생각해보십시오. 그리고 나서'var v = new ContactView ({model : m})'과'$ ('# contactList'). append (v.render(). 나는 내가보기가 자신의 '엘'을 완전히 소유하고 통제 할 때가 훨씬 더 나은 시간을 갖는다는 것을 안다. –

답변

2

이 줄 문제

new ContactView({ el: $el, model: m.attributes }); 

m.attributesis a plain js object의 원천입니다. 당신은 실제 모델 객체를 따라 전달하려는 :

new ContactView({ el: $el, model: m}); 

그리고 the collection has underscore methods mixed in 때문에 당신이 그것을 조금 단순화 할 수 있어야한다 :

contactList.each(function (m) { 
     var $el = $('<li />') 
      .addClass('adminItem clearfix') 
      .appendTo($('#contactList')); 
     new ContactView({ el: $el, model: m}); 
    }); 
+0

고맙습니다. 이전 방식으로 모델을 할당 할 때 뷰를 렌더링하는 데 문제가있었습니다. 그래서 마지막 비트 - 이제 깨닫습니다 - unserscore의'_template'에'this.model '대신'this.model.attrbutes'를 전달해야합니다. – Faust

관련 문제