2014-01-13 28 views
1

原諒我,我是新來的骨幹和MVC javascript概念。Backbone.js獲取列表以確保只存在某個模型的一個實例

所以,我想提出一個評價系統:

createComment: function() { 
     // create new comment model 

     var comment = new CommentModel({}); 

     // render form view right after new button 
     var formview = new FormView({model: comment}); 
     this.$el.after(formview.render().$el); 

     // add saved model to collection after form was submitted successfully 
     formview.on('success', this.handleFormSuccess, this); 

     // finally, return false to stop event propagation 
     return false; 
    }, 

什麼我不明白是怎麼弄的已經賦予評論列表,但尚未發送到集合。看,我想確保一次只打開一個評論框。

我的方法是檢查看看有多少評論已打開,並關閉除當前模型以外的所有人。

Using Backbone.js & Underscore, how to get a count of items from the model?似乎給出瞭如何做到這一點的建議該模型命中一個集合。

我是非常新的骨幹,所以這是完全可能的,我在這個確切的錯誤方向。

如何獲取列表?

+0

'成功'不是觸發器。應該是'同步' – Joe

回答

0

喬建議,我覺得你的問題是這一行:

formview.on('success', this.handleFormSuccess, this); 

不過,我不認爲他的建議,要麼工作(改變「成功」到「同步」的),因爲formview是一個查看,而不是模型集合,所以它甚至沒有一個on方法。

是什麼有on方法是視圖的元素,所以你可以做:

formview.$el.on('success', this.handleFormSuccess, this); 

兩個問題,雖然:

  1. jQuery是瘸腿的,不會讓你設置像這樣的背景
  2. 「成功」不是形式事件;你想這個代碼觸發「提交」

所以解決您需要更改行這兩個問題:

formview.$el.on('submit', _(this.handleFormSuccess).bind(this)); 

另外,您也可以撥打:

_(this).bindAll('handleFormSuccess'); 

FormViewinitialize,這會使你不需要綁定this.handleFormSuccess)

formview.$el.on('submit', this.handleFormSuccess); 

希望有幫助。

+0

P.S.如果你使'handleFormSuccess'成爲'FormView'的一個方法,而不是一成不變的查看,你可以避免必須處理綁定。在這種情況下,您可以使用'events:'submit':'handleFormSuccess')來完全消除該行的需要。 – machineghost

相關問題