2014-01-25 60 views
0

我試圖用這個 嘗試過濾一個特定的數據。backbonejs過濾數據時傳遞參數

在菜單中,我有一個lista,我希望當我點擊一個我只能得到關於它的信息。

HourView= Backbone.View.extend({  


    initialize: function(){   
     this.template = _.template($("#HourView").html()); 
    }, 
    render: function() { 
     var col = new HourCollection();  

     $.ajax({ //zeptojs 
     async: true 
     }); 
     col.fetch({ success: function() { 

     }}); 

     //col.fetch({reset: true}); 
     $.ajax({ //zeptojs 
     async: false 
     });   
     col.where({"name": "Gamarra"}); 


     this.$el.html(this.template({ horarios: col.toJSON() }));   
     return this; 
    } 
}); 

[ { 「名稱」: 「加馬拉」, 「VES」:[ 「00:00」 ], 「GRAU」:[ 「01:00」 ] } , { 「名稱」: 「格勞」, 「VES」:[ 「08:00」 ], 「GRAU」:[ 「07:00」 ] } ]

我想這

initialize: function(){ 
     this.collection = new HourCollection();   
     this.collection.fetch({reset: true}); 
     this.collection.fetch({success: function(collection) { 
      collection = collection.where({"name": "Gamarra"}); 
      console.log(JSON.stringify(collection))   
     }});    

     this.collection.on("sync", this.render, this); 

     this.template = _.template($("#HourView").html() );    
    }, 
    render: function() { 
     this.$el.html(this.template({ hs: this.collection.toJSON() }));   
     return this; 
    } 
+0

{ \t \t \t col.where({「nombre」:「Gamarra」}); \t \t}});但它不工作......以及 – Osgux

+0

該代碼中是否存在copy'n'paste錯誤? Zepto支持'async:true'嗎?你爲什麼不在'col'上使用事件來觸發渲染?通常情況下,你需要在'initialize','col.fetch({reset:true})'中實例化這個集合,然後監聽''reset''事件來觸發'render'(或多或少)。 –

+0

是的,但我需要這部分「[{」nombre「:」Gamarra「,」VES「:[」00:00「],」GRAU「:[」01:00「]}]」 – Osgux

回答

1

where返回與模式陣列(未收集)的方法,所以你可以用下劃線來調用每個模型toJSON方法,因此它看起來就像一個toJSON,但過濾。

this.$el.html(this.template({ hs: _.invoke(this.collection.where({"name": "Gamarra"}), 'toJSON') })); 

第二種方式就是在JSON

使用過濾器
this.$el.html(this.template({ hs: _.where(this.collection.toJSON(), {name: "Gamarra"}) })); 

第三個方法是使用在收集chain方法(順便說一句它不會對你的數據工作:(我不知道爲什麼,當我使用「其中」,是因爲我需要的JSON的特定部分,然後顯示在模板col.fetch({成功:()函數返回一個空數組)

this.collection.chain().where({ name: "Gamarra" }).value() 
+0

我想這個解析:功能(響應){ \t \t \t的console.log(JSON.stringify(反應[THIS.VALUE]))\t \t \t \t \t \t返回反應[THIS.VALUE]; \t \t} var hourCollection = new HourCollection(value); 它的工作原理,但認爲我不能刷新元素或數據.. – Osgux

+0

它的作品謝謝:) – Osgux