2012-06-07 3 views
1

У меня проблема с collection.get и model.get, возвращающая undefined.Collection.get Возврат undefined в backbone.js

вот мой initializecode

initialize: function() { 
    this.collection = new productsCollection(); 
    this.model = new productModel(); 
} 

вот мой код визуализации

this.collection.fetch({ 
    success: function (product) { 
     console.log(product); 
     $(that.el).html(_.template(productListTemplate, { products: product.models, _: _ })); 
    } 
}); 

мой список продуктов отображения в порядке. когда я нажимаю на каждый продукт я получаю всплывающее окно, где можно изменить имя

я хочу, чтобы получить набор нового имени в модели и триггере экономии

, но я не могу получить модель продукта здесь является код

$("#productName").val($(e.currentTarget).html()); 

var ID = $(e.currentTarget).data("id"); 
var item = this.collection.get(ID); 

console.log("start.........."); 
console.log(item); 
console.log(ID) 
//   console.log(this.collection); 
console.log(this.model.get(item)); 
console.log("end.........."); 

$('.modal').modal('toggle'); 

Я могу получить правильный идентификатор в консоли, но не коллекции и модели

может кто-нибудь помочь заранее спасибо

UPDATE здесь полный код вид

function ($, _, Backbone, popupModal, productTab, productsCollection, productListTemplate, productModel) { 
    var productListView = Backbone.View.extend({ 
     el: $("#page"), 
     initialize: function() { 
      this.collection = new productsCollection(); 
      this.model = new productModel(); 
      this.model.bind('change', this.loadResults, this); 
     }, 
     render: function() { 
      this.loadResults(); 
     }, 
     loadResults: function() { 
      var that = this; 
      this.collection.fetch({ 
       success: function (product) { 
        console.log(product); 
        $(that.el).html(_.template(productListTemplate, { products: product.models, _: _ })); 
       } 
      }); 
      var modalWindow = $(".modal").modal({ 
       show: false, 
       backdrop: true, 
       closeOnEscape: true 
      }); 
      $('#createProduct').click(function (e) { 
       this.modalWindow.modal('show'); 
      }); 
     }, 
     // This will simply listen for scroll events on the current el 
     events: { 
      "click #saveProduct": "saveProduct", 
      "click .productTabs": "productTabs", 
      "click .productDetails": "productDetails" 
     }, 
     saveProduct: function() { 
      this.model.set({ 
       Name: $('#productName').val() 
      }); 
      this.model.save({ id: this.model.get('id') }, 
     { 
      success: function (model, response) { 
       //     console.log("success"); 
      }, 
      error: function (model, response) { 
       //     console.log(response); 
       var errorMsg = JSON.parse(response.responseText); 
       $(".errorMessage").html('<div class="alert alert-error">' + errorMsg.Error + '</div>'); 
      } 
     }); 
     }, 
     productTabs: function (e) { 
      e.preventDefault(); 
      $(this).tab('show'); 
     }, 
     productDetails: function (e) { 
      e.preventDefault(); 
      $("#productName").val($(e.currentTarget).html()); 
      var ID = $(e.currentTarget).data("id"); 
      var item = this.collection.get(ID); 
      console.log("start.........."); 
      console.log(item); 
      console.log(ID) 
      //   console.log(this.collection); 
      console.log(this.collection.models.get(item)); 
      console.log("end.........."); 
      $('.modal').modal('toggle'); 
     } 
    }); 
    return new productListView; 
}); 

UPDATE ответы

this.collection

b.hasOwnProperty.e 
_byCid: Object 
_byId: Object 
_onModelEvent: function() { [native code] } 
_removeReference: function() { [native code] } 
length: 2 
models: Array[2] 
0: b.hasOwnProperty.e 
1: b.hasOwnProperty.e 
length: 2 
__proto__: Array[0] 
__proto__: s​ 

Он имеет 2 модели и мой список также имеет 2 продукты

this.model

_callbacks: Object 
_changed: false 
_changing: false 
_escapedAttributes: Object 
_previousAttributes: Object 
attributes: Object 
ID: "" 
Name: "" 
hRef: "" 
__proto__: Object 
cid: "c2" 
__proto__: s 

Атрибуты пустые

это дает мне следующее

cid: "view1" 
collection: b.hasOwnProperty.e 
_byCid: Object 
_byId: Object 
_onModelEvent: function() { [native code] } 
_removeReference: function() { [native code] } 
length: 2 
models: Array[2] 
__proto__: s 
model: b.hasOwnProperty.e 
_callbacks: Object 
_changed: false 
_changing: false 
_escapedAttributes: Object 
_previousAttributes: Object 
attributes: Object 
cid: "c2" 
__proto__: s 
options: Object 
__proto__: s 

UPDATE Это то, что я вижу, когда я расширить свои коллекции

b.hasOwnProperty.e 
_byCid: Object 
_byId: Object 
_onModelEvent: function() { [native code] } 
_removeReference: function() { [native code] } 
length: 2 
models: Array[2] 
0: b.hasOwnProperty.e 
_callbacks: Object 
_changed: false 
_changing: false 
_escapedAttributes: Object 
_previousAttributes: Object 
attributes: Object 
ID: "7e0c94fc-7c16-45c9-84a9-a0690103b946" 
Name: "dsa" 
hRef: "Product/dsa" 
__proto__: Object 
cid: "c3" 
collection: b.hasOwnProperty.e 
__proto__: s 
1: b.hasOwnProperty.e 
length: 2 
__proto__: Array[0] 
__proto__: s 
+0

код примера здесь очень _dismembered_, мы не можем видеть, как одна часть взаимодействует с другими. Просьба представить более последовательный и завершенный примерный код. – fguillen

+0

@fguillen Я опубликовал весь код – Kishore

+0

Что вы видите, когда вы запускаете прокомментированную строку 'console.log (this.collection);'? также, что вы видите, если вы запустите 'console.log (this.model);'? .. даже 'console.log (this);'? – fguillen

ответ

2

Проблема заключается в том, что вы должны связать все функции, которые будут вызывать с помощью DOM события, к примеру вашего зрения:

Так добавьте эту строку в ваш initialize метод:

_.bindAll(this, "saveProduct", "productTabs", "productDetails") 

В противном случае this в функции будет глобальный объект window вместо экземпляра вашего представления.

0

Если

Collection.findWhere({_id: ID}) // get the right answer 

мы можем заключить, что:


Например:

var Model = Backbone.Model.extend(); 
var Col = Backbone.Collection.extend({ model: Model }); 

var Persons = new Col([{ 
    _id: 1, 
    name: 'Ken' 
}, { 
    _id: 2, 
    name: 'Mike' 
}, { 
    _id: 3, 
    name: 'John' 
}]); 

console.log(Persons.get(1)); // undefined 

Если указать idAttribute М:

var M = Backbone.Model.extend({ idAttribute: '_id' }); 
... 
console.log(Persons.get(1)); // the model of Ken 

В некоторых случаях нам не нужны модели, такие как:

var Col = Backbone.Collection.extend(); 

var Persons = new Col([{ 
    _id: 1, 
    name: 'Ken' 
}, { 
    _id: 2, 
    name: 'Mike' 
}, { 
    _id: 3, 
    name: 'John' 
}]); 

console.log(Persons.get(2)); // undefined 

Для решения этой проблемы нам просто нужно переписать оригинал modelId метод:

var Col = Backbone.Collection.extend({ 
    modelId: function() { 
     return '_id'; 
    } 
}); 
... 
console.log(Persons.get(2)); // the model of Mike 


P.S: более подробно в official docs.


P.S снова: Старые версии BackboneJS не поддерживают ModelID

Смежные вопросы