2014-02-16 2 views
1

개체 배열 형식의 회사라는 백본 모델 변수가 있습니다. 콘솔에 놓음으로써 나는이 얻을 :개체 배열에서 특성을 얻으려면 어떻게해야합니까?

이 개체는 인출 기능이로드됩니다

require(["collections/Companies"], 
    function(Companies) { 
    var companies = new Companies(); 
    companies.fetch(); 
    console.log(companies[0].get("name")); 

}); 

companies

companies.js :

define([ 
    'models/Company' 
], function(CompanyModel) { 
    'use strict'; 

    var CompanyCollection = Backbone.Collection.extend({ 
     model: CompanyModel, 
     url: 'scripts/data/companies.json' 
    }); 

    return CompanyCollection; 
}); 

company.js를 :

define([], function() { 
    'use strict'; 

    var CompanyModel = Backbone.Model.extend({ 
     defaults: { 
      id: '', 
      name: '', 
      description: '' 
     } 
    }); 

    return CompanyModel; 
}); 

행운이없는 tutorials (console.log(companies[0].get("name"));)에 따라 get을 사용하여 속성을 가져 오려고했습니다.

속성을 가져 오는 올바른 구문은 무엇입니까? name 이후

+0

기업 [0] .attributes.name' 또는 회사 [0] .attributes [ "name"]'스크린 샷에 표시된 방식에 액세스하십시오! :) – MackieeE

+0

회사 [0] .attributes.name 또는 회사 [0] .attributes [ "name"]이 (가) TypeError를 throw합니다. 회사 [0]이 (가) 로그에 정의되지 않았습니다. – xanyi

+0

바닐라 자바 ​​스크립트처럼 DOMNode 속성에 액세스하는 방법은 확실합니다. – MackieeE

답변

2

당신이 백본 수집 방법 사용할 수 있습니다 컬렉션 모델을 얻으려면 - collection.at (INDEX)를;

예제 코드 :

var collection = new Backbone.Collection(); 
collection.add({ id: 1, name: "S"}); 
collection.add({ id: 2, name: "F"}); 

console.log(collection.at(0).attributes); // { id: 1, name: "S"} 

var model = collection.at(0); 

// get attributes from model 

console.log(model.get("name")); // "S" 

당신은 수집 사용으로 모델을 얻으려면 demo

으로 재생할 수 있습니다 : collection.models 그냥 두 번째 사진에서

1

객체입니다 attributes 내부 속성입니다 사전에

감사합니다, 당신은 사용할 수 있습니다 : 인쇄중인 오브젝트가 백본 컬렉션

console.log(companies[0].attributes.name); 
+0

회사 [0] .attributes.name 또는 회사 [0] .attributes [ "name"]이 (가) TypeError를 throw합니다. companies [0]은 로그에서 정의되지 않았습니다. – xanyi

+0

@ xanyi 코드에서'회사 [0]'은 무엇입니까? – Felix

+0

모델을 어떻게 초기화합니까? 코드를 게시 할 수 있습니까? – Felix

0

입니다. 배열 collection.models을 사용하여 모델에 액세스해야합니다.

var name = companies.models[0].get("name"); 

는 문서에 따라, 당신은 모델 ID 또는 collection.at 방법 지정된 인덱스를 사용하여 주어진 collection.get 방법을 사용하여 모델에 액세스해야합니다.

그래서, 당신은 당신의 회사의 개체에 액세스 할 수있는 등 :

var company = companies.get(1000001); 
var name = company.get("name"); 

문서 : http://backbonejs.org/#Collection-models

+0

TypeError : 회사가 작성한 코드와 정확히 일치하지 않습니다. – xanyi

0

을 (당신이 모델의 배열을 얻을 것이다) 이게 작동해야합니다 :

require(["collections/Companies"], 
    function(Companies) { 
    var companies = new Companies(); 
    companies.fetch(); 
    for (var idx in companies){ 
     console.log(companies[idx].attributes.name); 
    } 
}); 

companies[0]companies[1000001]companies[1000002].

+0

인덱스가 1000001 및 1000002이지만 회사 [anything]는 아직 정의되지 않은 것으로 알고 있습니다. – xanyi

관련 문제