2015-11-05 1 views
0

Я создал пользовательский объект, содержащий модели внутри коллекции, когда я выбираю этот объект в ItemView как this.options.unique Я не могу запустить .toJSON, так как получаю сообщение об ошибке Uncaught TypeError: this.options.unique.toJSON is not a function. Интересно, как я могу это исправить?Как запустить toJSON на объект из обновленной коллекции в Marionette ItemView?

Fiddlehttp://jsfiddle.net/kyllle/73m2ena9/3/

JS

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


var PersonsItemView = Mn.ItemView.extend({ 
    template: '.js-tmpl', 

    templateHelpers: function() { 
     return { 
      unique: this.options.unique 
     } 
    }, 

    initialize: function() { 
     console.log(this.options.unique.toJSON()); 
    } 
}); 


var peopleCollection = new PeopleCollection(peopleArr); 

var unqiueList = peopleCollection.filter(function(person) { 
    include = true; 
    exclude.forEach(function(exl) { 
     console.log(exl); 
     if (JSON.stringify(exl) == JSON.stringify(person)) { 
      include = false; 
      return; 
     } 
    }) 
    if (include) return person; 
}); 

console.log(unqiueList); 

var personsView = new PersonsItemView({ 
    unique: unqiueList 
}); 


var region = new Backbone.Marionette.Region({ 
    el: '.js-ctn' 
}); 

region.show(personsView); 

UPDATE Я добавил переменную внутри шаблона each, чтобы захватить модель и превратить toJSON, может кто-нибудь посоветовать, если этот подход приемлемо?

<script type="text/html" class="js-tmpl"> 
<form action=""> 
    <% _.each(unique, function(person) { %> 
     <% var personDetails = person.toJSON() %> 
     <input type="radio"><%= personDetails.name %><br> 
    <% }) %> 
</form> 

Обновлено скрипку http://jsfiddle.net/kyllle/73m2ena9/7/

ответ

1

При фильтрации коллекции он возвращает массив не коллекцию, как вы ожидали (ref). Таким образом, вы можете создать новый экземпляр коллекции с массивом, возвращаемым из коллекции.

var unqiueList = peopleCollection.filter(function(person) { 
    include = true; 
    exclude.forEach(function(exl) { 
     console.log(exl); 
     if (JSON.stringify(exl) == JSON.stringify(person)) { 
      include = false; 
      return; 
     } 
    }) 
    if (include) return person; 
}); 

unqiueList= new peopleCollection.reset(unqiueList); 

var personsView = new PersonsItemView({ 
    unique: unqiueList 
}); 

FIDDLE LINK

+0

Спасибо, но это, кажется, не работает должным образом? Я получаю ошибку шаблона еще – styler

+0

Когда я выхожу из персонажа внутри шаблона 'each', я вижу undefined? – styler

+0

Эй, я не знаю, как работает Marionette с шаблоном и данными, просто просмотрите документы. – StateLess