2015-11-05 20 views
0

我在一個集合中創建了一個包含模型的自定義對象,當我在ItemView中選擇這個對象爲this.options.unique我無法運行.toJSON,因爲出現錯誤Uncaught TypeError: this.options.unique.toJSON is not a function。想知道如何解決這個問題?如何在Marionette ItemView中的更新集合的對象上運行toJSON?

小提琴http://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

當我註銷模板內的每個人時,我看到未定義? – styler

+0

嘿,我不知道Marionette如何使用模板和數據,只需查看文檔即可。 – StateLess

相關問題