2012-01-27 3 views
0

У меня возникли проблемы с использованием jQuery.append() и backbonejs. Как и сейчас, когда он пытается добавить, ничего не происходит (кроме того, что он возвращает объект jQuery [увиденный в ближайшем окне]), счет еще равен 0. Ive попытался добавить элемент вручную, без успеха. Ive также попытался добавить, используя только string(), и это по какой-то причине работает. Мысль здесь состоит в том, чтобы загрузить некоторые объекты в pageload и изменить его selectate selectbox на основе значения, выбранного в первом поле. Но я, как вы видите, немного застрял. (Что раздражает такой тривиальной вещи, как это). Источник я использовал в качестве руководства можно найти здесь: https://github.com/shinetech/CascadingSelectsWithBackboneJS/blob/master/public/javascripts/application.jsBackbone.js - проблема с использованием jQuery append

$(function() { 
    window.AgfaRis = Backbone.View.extend({ 
     template: _.template($("#agfaris-template").html()), 

     initialize: function() { 
      _.bindAll(this, "render"); 
     }, 

     render: function() { 
      $(this.el).html(this.template(this.model.toJSON())); 
      this.EstablishHospitals(); 
      return this; // MUST return this 
     }, 

// RELEVANT STUFF FROM HERE ON 
     EstablishHospitals: function() { 
      var hospitals = new Hospitals(); 
      hospitals.url = "/_Systemer/AgfaRis/GetHospitals/" + this.model.attributes.Id; 

      var hospitalsView = new HospitalsView({el: $("#Hospitals"), collection: hospitals}); 
      var hospitalRolesView = new HospitalRolesView({el: $("#HospitalRoles"), collection: new HospitalRoles()}); 

      hospitalsView.hospitalRolesView = hospitalRolesView; 
      hospitals.fetch(); 
     } 
    }); 


    var Hospital = Backbone.Model.extend(); 
    var HospitalRole = Backbone.Model.extend(); 
    var Hospitals = Backbone.Collection.extend({ model: Hospital }); 
    var HospitalRoles = Backbone.Collection.extend({ model: HospitalRole }); 

    var LocationView = Backbone.View.extend({ 
     tagName: "option", 

     initialize: function() { 
      _.bindAll(this, "render"); 
     }, 

     render: function() { 
      $(this.el).attr('value', this.model.get('Id')).html(this.model.get('Name')); 
      return this; 
     } 
    }); 

    var LocationsView = Backbone.View.extend({ 
     events: { 
      "change": "changeSelected" 
     }, 

     initialize: function() { 
      _.bindAll(this, 'addOne', 'addAll'); 
      this.collection.bind('reset', this.addAll); 
     }, 

     addOne: function(location) { 
      var locationView = new LocationView({ model: location }); 
      this.locationViews.push(locationView); 
      $(this.el).append(locationView.render().el); 
     }, 

     addAll: function() { 
      _.each(this.locationViews, function(locationView) { locationView.remove(); }); 
      this.locationViews = []; 
      this.collection.each(this.addOne); 
      if(this.selectedId) { 
       $(this.el).val(this.selectedId); 
      } 
     }, 

     changeSelected: function() { 
      this.setSelectedId($(this.el).val()); 
     }, 

     populateFrom: function(url) { 
      this.collection.url = url; 
      this.collection.fetch(); 
      this.setDisabled(false); 
     }, 

     setDisabled: function(disabled) { 
      $(this.el).attr('disabled', disabled); 
     } 
    }); 

    var HospitalsView = LocationsView.extend({ 
     setSelectedId: function(hospitalId) { 
      this.hospitalRolesView.selectedId = null; 
      this.hospitalRolesView.setHospitalId(hospitalId); 
     } 
    }); 

    var HospitalRolesView = LocationsView.extend({ 
     setHospitalId: function(hospitalId) { 
      this.populateFrom("/_Systemer/AgfaRis/GetHospitalRoles/" + hospitalId); 
     } 
    }); 
}); 

отладочные данные

this.model.get('Id') and .get('Name') works, they return the value and text seen below. 

(HtmlOptionElement) 
this.locationViews[0].render().el 
{...} 
    defaultSelected: false 
    form: null 
    index: 0 
    label: "" 
    selected: false 
    text: "--- Velg Sykehus ---" 
    value: "--- Velg Sykehus ---" 
    dataFld: "" 
    dataFormatAs: "" 
    dataSrc: "" 
    currentStyle: {...} 
    runtimeStyle: {...} 
    accessKey: "" 
    className: "" 
    contentEditable: "inherit" 
    dir: "" 
    disabled: false 
    id: "" 
    innerHTML: "--- Velg Sykehus ---" 
    isContentEditable: false 
    lang: "" 
    offsetHeight: 0 
    offsetLeft: 0 
    offsetParent: null 
    offsetTop: 0 
    offsetWidth: 0 
    onabort: null 
    onblur: null 
    oncanplay: null 
    oncanplaythrough: null 
    onchange: null 
    onclick: null 
    oncontextmenu: null 
    ondblclick: null 
    ondrag: null 
    ondragend: null 
    ondragenter: null 
    ondragleave: null 
    ondragover: null 
    ondragstart: null 
    ondrop: null 
    ondurationchange: null 
    onemptied: null 
    onended: null 
    onerror: null 
    onfocus: null 
    oninput: null 
    onkeydown: null 
    onkeypress: null 
    onkeyup: null 
    onload: null 
    onloadeddata: null 
    onloadedmetadata: null 
    onloadstart: null 
    onmousedown: null 
    onmousemove: null 
    onmouseout: null 
    onmouseover: null 
    onmouseup: null 
    onmousewheel: null 
    onpause: null 
    onplay: null 
    onplaying: null 
    onprogress: null 
    onratechange: null 
    onreadystatechange: null 
    onreset: null 
    onscroll: null 
    onseeked: null 
    onseeking: null 
    onselect: null 
    onstalled: null 
    onsubmit: null 
    onsuspend: null 
    ontimeupdate: null 
    onvolumechange: null 
    onwaiting: null 
    outerHTML: "<option value="--- Velg Sykehus ---">--- Velg Sykehus ---</option>" 
    style: {...} 
    tabIndex: 0 
    title: "" 
    all: {...} 
    behaviorUrns: {...} 
    canHaveChildren: true 
    canHaveHTML: true 
    children: {...} 
    document: {...} 
    filters: {...} 
    hideFocus: false 
    innerText: "--- Velg Sykehus ---" 
    isDisabled: false 
    isMultiLine: true 
    isTextEdit: false 
    language: "" 
    onactivate: null 
    onafterupdate: null 
    onbeforeactivate: null 
    onbeforecopy: null 
    onbeforecut: null 
    onbeforedeactivate: null 
    < More... (The first 100 of 259 items were displayed.) > 


<select id="Hospitals"> 
    <option value="">Select</option> 
</select><br /> 
<select id="HospitalRoles"> 
    <option value="">Select</option> 
</select> 
+0

Как примечание стороны, нет никаких ошибок и все работает (за исключением добавьте операцию) – tskulbru

ответ

0

да там всегда будут проблемы с добавлением элемента «OPTIONS» в SELECT, элементом. Если удалить VIEW LocationView и не добавляя с this.el.options.add тогда вы не будете иметь никакого Probs ...

http://www.w3schools.com/jsref/coll_select_options.asp